两数之和

Posted on 2018-09-05 11:50  otonashi  阅读(153)  评论(0)    收藏  举报

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

 

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            int x=target-nums[i];
            if(map.containsKey(x)){
                return new int[] {map.get(x),i};
            }
            map.put(nums[i],i);
        }
         throw new IllegalArgumentException("No two sum solution");
    }
}

 

 

 

 因为for循环可能导致无返回值时,可抛出异常解决。