package Easy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Demo1 {
public static void main(String[] args) {
int[] nums = {2, 7, 11, 15};
int t = 26;
int[] arr = twoSum(nums, t);
System.out.println(Arrays.toString(arr));//printout is supposed to be [2,3],however it's [3, 4],what's wrong?
}
public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[1] = i + 1;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i + 1);
}
return result;
}
}
printout应该是[2,3],不过它[3,4],有什么不对吗?谢谢你的帮助。
描述: 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。
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].
答案 0 :(得分:0)
你的方式很复杂,你可以用更简单的方法解决它:
int[] nums = {2, 7, 11, 15};
ArrayList<Integer> index = new ArrayList<Integer>();
int t = 26;
for(int i=0 ; i < nums.length-1 ; i++){
for(int j=i+1 ; j < nums.length ; j++){
if(nums[i] + nums[j] == t){
index.add(i);
index.add(j);
}
}
}
System.out.println(index);
输出:
[2, 3]