题目:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
解题思路:
1.hash即可。将所有的数组插入到map中,然后 遍历数组nums[i],同时在map中查找target-nums[i]的元素。空间复杂度为O(N),时间复杂度为O(N);
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int,int> cnt; map<int,int>::iterator it; vector<int> res; for(int i = 0;i < nums.size();++i){ cnt[nums[i]] = i; } for(int i = 0;i < nums.size(); ++i){ if((it = cnt.find(target-nums[i]))!=cnt.end()){ if(it->second != i){ res.push_back(i); res.push_back(it->second); return res; } } } return res; } };
2.双层循环遍历即可寻找nums[i] + nums[j] == target.
int* twoSum(int* nums, int numsSize, int target) { for(int i = 0;i<numsSize-1;i++){ for(int j = i+1;j<numsSize;j++){ if(target == (nums[i]+nums[j])){ int * numResult = (int *)malloc(sizeof(int)*2); numResult[0] = i; numResult[1] = j; return numResult; } } } return NULL; }
3.如果是排序好的数组,则可以用二分查找来实现:
int binarySearch(vector<int> &nums,int left,int right,int target){ while(left <= right){ int mid = (left+right)/2; if(nums[mid] == target){ return mid; }else if(nums[mid] > target){ right = mid - 1; }else{ left = mid + 1; } } return -1; } vector<int> twoSum(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); vector<int> res; for(int i = 0; nums[i] < target; ++i){ int key = 0; if((key = binarySearch(nums,i+1,nums.size(),target-nums[i])) > 0){ res.push_back(i); res.push_back(key); return res; } } return res; }