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].
题目大意:给定一个数组和一个数target,输出数组中两个数之和为target的下标。
理 解 :方法一:暴力法,直接遍历数组,访问第i个数,判断target - nums[i] 是否存在数组中。时间复杂度为O(n^2),空间复杂度O(1).
方法二:哈希法,哈希查找的时间是几乎线性的,遍历数组时,访问第i个数,判断target - nums[i] 是否存在哈希表中,否则将当前数值nums[i]和下标[i]存在哈希表。
代 码 C++:
方法一 -- 暴力法:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> vec; int n = nums.size(); for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ if(target-nums[i]==nums[j] && i!=j){ vec.push_back(i); vec.push_back(j); } } } return vec; } };
方法二 -- 哈希表法:
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> vec; unordered_map<int,int> map; int n = nums.size(); for(int i=0;i<n;++i){ unordered_map<int,int>::iterator it; it = map.find(target-nums[i]); if(it!=map.end()){ vec.push_back(i); vec.push_back(it->second); break; } map.insert(make_pair(nums[i],i)); } return vec; } };