LC#1

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数,且同样的元素不能被重复利用。

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

猜你喜欢

转载自www.cnblogs.com/otonashi/p/9591300.html
lc1