题目地址:https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/
题目描述
输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。
题目示例
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[2,7] 或者 [7,2]
示例 2:
输入:nums = [10,26,30,31,47,60], target = 40
输出:[10,30] 或者 [30,10]
解题思路
方法1:使用哈希表解决,具体思路设置哈希表的key值为nums[i],value值是target - nums[i],然后利用迭代器查找target - nums[i],如果有以target - nums[i]为键值的值,则其值为nums[i],将nums[i]和target - nums[i]装入结果向量arr中,否则将target - nums[i]放进哈希表中。
方法2:双指针解法,根据题目可知,数组单调递增,所以设置两个指针low和high分别指向数组nums两端,如果两者之和sum大于target,则右指针左移,即high--,否则左指针右移,即low++
方法3:暴力破解,两层循环解决,但是超时。
程序源码
方法1:哈希表
case1
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> res; vector<int> arr; if(nums.size() < 2) return nums; for(int i = 0; i < nums.size(); i++) { res[nums[i]] = 1; //初始化 } for(int i = 0; i < res.size(); i++) { if(res[target - nums[i]] != 0) { arr.push_back(nums[i]); arr.push_back(target - nums[i]); break; } } return arr; } };
case2
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> mp; vector<int> arr; for(int i = 0; i < (int)nums.size(); i++) { auto iterator = mp.find(target - nums[i]); if(iterator != mp.end()) { arr.push_back(nums[i]); arr.push_back(target - nums[i]); break; } else mp[nums[i]] = target - nums[i]; } return arr; } };
方法2:双指针
case1——二分法
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { if(nums.size() < 2) return nums; int left = 0, right = nums.size() - 1; while(left < right) { if(nums[left] + nums[right] > target) right--; else if(nums[left] + nums[right] < target) left++; else return {nums[left], nums[right]}; } return nums; } };
case2
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> arr; if(nums.size() < 2) return nums; int low = 0, high = (int)nums.size() - 1; int sum = 0; while(low < high) { sum = nums[low] + nums[high]; if(sum == target) { arr.push_back(nums[low]); arr.push_back(nums[high]); break; } else if(sum > target) high--; else low++; } return arr; } };
方法3:暴力(超时)
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> res(2,0); int first_num = 0, second_num = 0; if(nums.size() < 2) return nums; for(int i = 0; i < nums.size() - 1; i++) { first_num = nums[i]; for(int j = i + 1; j < nums.size(); j++) { second_num = target - first_num; if(nums[j] == second_num) { res[0] = nums[i]; res[1] = nums[j]; } } } return res; } };
参考文章: