Python 实现行为驱动开发 (BDD) 自动化测试详解
128 Longest Consecutive Sequence

class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.empty())return 0;
unordered_map<int,int> hash;
for(int x : nums){
hash[x]++;
}
int ans = 0;
for(const auto& pair : hash){
int n = pair.first;
if(hash.find(n-1) == hash.end()){
int len = 1;
int current = n;
while(hash.find(current + 1) != hash.end()){
current++;
len++;
}
ans = max(ans,len);
}
}
return ans;
}
};
c++代码学习 unordered_set和map的区别
上述代码中,将nums存入hash可以用下列的代码代替
unordered_set<int> hash(nums.begin(),nums.end());
遍历时也就是
for(int n : hash){
}

138 Copy List with Random Pointer【默写】



class Solution {
public:
Node* copyRandomList(Node* head) {
if(!head) return nullptr;
Node* dummy = new Node(0);
Node* temp = dummy;
Node* p = head;
unordered_map<Node* , Node*> hash;
while(p){
Node* newNode = new Node(p->val);
hash[p] = newNode;
temp->next = newNode;
temp = temp->next;
p = p->next;
}
p = head;
temp = dummy->next;
while(p){
if(p->random){
temp->random = hash[p->random];
}
temp = temp->next;
p = p->next;
}
return dummy->next;
}
};