Leetcode 第2章 线性表

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,nk1}) .

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
主要步骤如下:

  1. 从右往左找到第一个不满足递增规则的数,成为Partition Number.
  2. 再次从右往左找第一个比Partition Number更大的数值,叫做Changer Number.
  3. 交换Partithon Number和Change Number.
  4. 将Partition Index右边的所有数字都反序.
2.1.13Permutation Sequence
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值