1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
解法1:暴力法。时间复杂度为O(n^2),空间复杂度为O(1)
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> res; 5 if(nums.size()<2)return res; 6 for(size_t i=0; i<nums.size(); ++i) 7 { 8 for(size_t j=i+1; j<nums.size(); ++j) 9 { 10 if(nums[i]+nums[j]==target) 11 { 12 res.push_back(i); 13 res.push_back(j); 14 return res; 15 } 16 } 17 } 18 return res; 19 } 20 };
解法2:用一个hash表(c++中可使用unordered_map)记录下出现过的数字及其对应的位置,以空间换时间,可将时间复杂度降低到O(n),空间复杂度为O(n)
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> res; 5 std::unordered_map<int, int> hashMap; 6 for(size_t idx=0; idx<nums.size(); ++idx) 7 { 8 auto it=hashMap.find(target-nums[idx]); 9 if(it!=hashMap.end()) 10 { 11 res.push_back(it->second); 12 res.push_back(idx); 13 return res; 14 }else{ 15 hashMap.insert(std::make_pair(nums[idx], idx)); 16 } 17 } 18 return res; 19 } 20 };