128. Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2]
,
The longest consecutive elements sequence is [1, 2, 3, 4]
. Return its length: 4
.
Your algorithm should run in O(n) complexity.
Solution: 哈希表存储后,两头查询。Code:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int,bool> m;
for(auto i:nums) m[i] = false; //遍历的简化写法,auto:自动判断变量类型
int maxlength = 0;
for(auto i:nums){
if(m[i]==true) continue;
else{
int min = i;
int max = i;
int length = 1;
int end = false;
while(!end){
end = true;
if(m.find(min-1)!=m.end()){
m[min-1] = true;
min--;
length++;
end = false;
}
if(m.find(max+1)!=m.end()){
m[max+1] = true;
max++;
length++;
end = false;
}
}
if(maxlength<length) maxlength = length;
}
}
return maxlength;
}
};
16. 3Sum Closest
Solution: 排序之后,夹逼(不需要遍历)
Code:
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int cloSum = nums[0] + nums[1] + nums[2];
for(auto a = nums.begin(); a<prev(nums.end(),2);
a = upper_bound(a,prev(nums.end(),2),*a)){//得到下一个不重复的a值
auto b = next(a);
auto c = prev(nums.end());
while(b<c){
int sum = *a + *b + *c;
if(abs(sum-target)<abs(cloSum-target)){
cloSum = sum;
}
if(sum<target) b++;
else c--;
}
}
return cloSum;
}
};
18. 4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
Solution: 排序之后,两层遍历之后夹逼(不需要遍历)
Code:
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
if(nums.size()<4) return result;
sort(nums.begin(), nums.end());
for(auto a = nums.begin(); a<prev(nums.end(), 3);
a = upper_bound(a, prev(nums.end(), 3), *a)){
int t = target - *a;
for(auto b = next(a); b<prev(nums.end(),2);
b =upper_bound(b, prev(nums.end(),2), *b)){
auto c = next(b);
auto d = prev(nums.end());
while(c<d){
int sum = *b + *c + *d;
if(sum==t){
vector<int> r;
r.push_back(*a);
r.push_back(*b);
r.push_back(*c);
r.push_back(*d);
result.push_back(r);
c = upper_bound(c, prev(nums.end()), *c);
}else if(sum>t){
d = prev(d);
}else if(sum<t){
c = next(c);
}
}
}
}
return result;
}
};