public class TwoNums {
public static void main(String[] args) {
int[] arr = TwoNums.twoSum(9);
for(int a: arr) {
System.out.println(a);
}
}
public static int[] twoSum(int target) {
int[] nums = {2, 7, 11, 15};
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++) {
map.put(nums[i], i); //以数组的值为键,键为值,将数组分配到map键值对中
}
for(int j = 0; j < nums.length; j++){
int Difference = target - nums[j];
if(map.containsKey(Difference) && map.get(Difference) != j) { //是否包含该键,且键值不重复
return new int[] {j, map.get(Difference)};
}
}throw new IllegalArgumentException(); //抛出表示一种方法已经通过了非法或不正确的参数。
}
两数之和,HashMap复习
最新推荐文章于 2023-01-09 10:12:10 发布