题目如下:
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
twoSum问题是一道经典的题目,题目要求给定一个整数数组和一个目标整数target,在数组中查找一对数,满足它们的和正好是target。
解题思路:
使用target = a + b的性质,对数组进行操作。首先,将数组中的值逐个加入map中,然后,对target - nums[i]判断是否在map中,如果在map中说明a和b已经遍历过了,最后,将a、b对应的索引返回。提交的代码:
public int[] twoSum(int[] nums, int target) {
int[] index = new int[2];
int length = nums.length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < length; i++) {
//把数据存放在map中
if(!map.containsKey(nums[i])){
map.put(nums[i], i);
}
//判断map中是否存在target - nums[i]
if(map.containsKey(target - nums[i])){
int num = map.get(target - nums[i]);
if(num < i){
index[0] = num + 1;
index[1] = i + 1;
return index;
}
}
}
return index;
}