一、问题
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
问题描述:给定一个整数数组, 返回两个数字的索引, 使两个数字相加为到特定值。
Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]
二、解析
先遍历一遍数组,建立 HashMap 映射,然后再遍历一遍,开始查找,找到则记录 index。
1、Go 解法
func twoSum(nums []int, target int) []int {
maps := map[int]int{}
for index, value := range nums {
member := target - value
if key,ok := maps[member];ok{
return []int{key,index}
}else{
maps[value] = index
}
}
return nil
}
2、C++解法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
// Only really have to search if there's more than 2 elements...
if(nums.size() > 2){
// So... the known solution is to use a hashmap with the stored differences...
map<int,int> summer; // <number,index>
for(int i=0;i<nums.size();i++){
int theDiff = target-nums[i];
if(summer.find(theDiff)==summer.end()){
summer[nums[i]]=i;
} else {
return {summer[theDiff],i};
}
}
}
//If there's only 2 elements, obviously that's the answer then...
return {0,1};
}
};
3、JAVA解法
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
if (m.containsKey(target - nums[i])) {
res[0] = i;
res[1] = m.get(target - nums[i]);
break;
}
m.put(nums[i], i);
}
return res;
}
}