2.1数组
2.1.2 Remove Duplicates from Sorted Array II
Leetcode第80题https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
2.1.3 Search in Rotated Sorted Array
Leetcode第33题https://leetcode.com/problems/search-in-rotated-sorted-array/
2.1.4 Search in Rotated Sorted Array II
Leetcode第81题https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
2.1.5 Median of Two Sorted Arrays
Leetcode第4题https://leetcode.com/problems/median-of-two-sorted-arrays/
2.1.6 Longest Consecutive Sequence
Leetcode第128题https://leetcode.com/problems/longest-consecutive-sequence/
如果先排序后遍历,则时间复杂度为
O(nlogn)
,本题要求时间复杂度为
O(n)
,因此使用哈希表。
用一个哈希表unordered_map<int, bool> used
记录每个元素是否使用,对每个元素,以该元素为中心,往左右扩张,直到不连续为止,记录下最长的长度。
2.1.7 Two Sum
Leetcode第1题https://leetcode.com/problems/two-sum/
方法1:遍历,
O(n2)
,会超时
方法2:hash。用一个哈希表,存储每个数对应的下标,复杂度
O(n)
//LeetCode, Two Sum
// 方法 2:hash。用一个哈希表,存储每个数对应的下标
// 时间复杂度 O(n),空间复杂度 O(n)
class Solution {
public:
vector<int> twoSum(vector<int> &num, int target) {
unordered_map<int, int> mapping;
vector<int> result;
for (int i = 0; i < num.size(); i++) {
mapping[num[i]] = i;
}
for (int i = 0; i < num.size(); i++) {
const int gap = target - num[i];
if (mapping.find(gap) != mapping.end()) {
result.push_back(i + 1);
result.push_back(mapping[gap] + 1);
break;
} }
return result;
}
};
2.1.8 3Sum
Leetcode第15题https://leetcode.com/problems/3sum/
先排序,然后左右夹逼,复杂度
O(n2)
,这个方法可以推广到k-sum,然后k-2次循环,在最内层循环左右夹逼,时间复杂度为
O(max{nlogn,nk−1})
.
2.1.9 3Sum Closest
Leetcode第16题https://leetcode.com/problems/3sum-closest/
分析:先排序,然后左右夹逼,复杂度
O(n2)
2.1.10 4Sum
2.1.12 Next Permutation
算法参考:http://fisherlei.blogspot.com/2012/12/leetcode-next-permutation.html
主要步骤如下:
- 从右往左找到第一个不满足递增规则的数,成为Partition Number.
- 再次从右往左找第一个比Partition Number更大的数值,叫做Changer Number.
- 交换Partithon Number和Change Number.
- 将Partition Index右边的所有数字都反序.