【LeetCode 1_陣列_雜湊表】Two Sum

QingLiXueShi發表於2015-07-10

解法一:O(N)

 1 vector<int> twoSum(vector<int>& nums, int target)
 2 {
 3     unordered_map<int, int> numsHash;
 4     vector<int> res;
 5 
 6     for (int i = 0; i < nums.size(); ++i) {
 7         int num_last = target - nums[i];
 8         if (numsHash.find(num_last) != numsHash.end()) {
 9             res.push_back(numsHash[num_last] + 1);
10             res.push_back(i + 1);
11             break;
12         } else {
13             numsHash[nums[i]] = i;
14         }
15     }
16     return res;
17 }

解法二:O(NlogN)

 1 vector<int> twoSum(vector<int>& nums, int target)
 2 {
 3     vector<int> res;
 4     int lpos = 0, rpos = nums.size() - 1;
 5     sort(nums.begin(), nums.end());
 6     while (lpos < rpos) {
 7         int num = nums[lpos] + nums[rpos];
 8         if (num == target) {
 9             res.push_back(lpos + 1);
10             res.push_back(rpos + 1);
11         } else if (num > target) {
12             rpos--;
13         } else {
14             lpos++;
15         }
16     }
17     return res;
18 }

解法二也是不錯的思路,空間複雜度O(1),但這個解法會超時。

相關文章