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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
1 /* 2 利用hash表保存nums中的值和其下标 用target和nums中的值做差 在hash表中查找此差值是否存在 3 */ 4 class Solution 5 { 6 public: 7 vector<int> twoSum(vector<int>& nums, int target) 8 { 9 unordered_map<int, int> hash_map; 10 11 for (size_t i = 0; i < nums.size(); ++i) 12 { 13 hash_map[nums[i]] = i; // 把value和key存到hash表中 value作为键 下标作为值 14 } 15 16 vector<int> result; 17 18 for (size_t i = 0; i < nums.size(); ++i) 19 { 20 const int diff = target - nums[i]; // 差值 21 22 if (hash_map.find(diff) != hash_map.end() && hash_map[diff] > i) // 查找diff 并且注意下标大小 23 { 24 result.push_back(i); // 先push_back小的值 25 result.push_back(hash_map[diff]); 26 27 break; 28 } 29 } 30 31 return result; 32 } 33 };
1 // 暴力 会超时 O(n^2) 2 class Solution { 3 public: 4 vector<int> twoSum(vector<int>& nums, int target) { 5 if (nums.empty()) 6 { 7 return vector<int>(); 8 } 9 10 vector<int> tmp; 11 12 for (size_t i = 0; i < nums.size(); ++i) 13 { 14 for (size_t j = i + 1; j < nums.size(); ++j) 15 { 16 if (nums[i] + nums[j] == target) 17 { 18 tmp.push_back(i); 19 tmp.push_back(j); 20 21 break; 22 } 23 } 24 } 25 return tmp; 26 } 27 };