LeetCode01

Two Sum

给定一个数组和一个目标和,从数组中找两个数字相加等于目标和,输出这两个数字的下标。


answer1:

1
2
3
4
5
6
7
8
9
10
11
12
  public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int sub=target-nums[i];
if(map.containsKey(sub)){
return new int[]{i,map.get(sub)};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}

__END__