Number of 1 Bits
iven 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.
For example
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路
最简单的2重循环,自己也是这样想的
代码1 –2重循环
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
for(size_t it = 0;it<nums.size()-1;it++)
{
for(size_t it2 = it+1;it2<nums.size();it2++)
{
if(nums[it]+nums[it2]==target)
{
res.push_back(it);
res.push_back(it2);
return res;
}
}
}
}
};
代码2 –O(n)
用到了map,存nums[x],x
然后就在里面找target-nums[x]
这样找到第二个的时候,第一个肯定是配对好的了
public int[] twoSum(int[] nums, int target) {
if(nums==null || nums.length==0)
return null;
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int x=0;x<nums.length;x++){
if(map.containsKey(target-nums[x])){
result[1] = x;
result[0] = map.get(target-nums[x]);
}
map.put(nums[x],x);
}
return result;
} };