2018.3.12 Leecode习题 给定一个整数数列,找出其中和为特定值的那两个数。

给定一个整数数列,找出其中和为特定值的那两个数。

你可以假设每个输入都只会有一种答案,同样的元素不能被重用。

示例:
给定 nums = [2, 7, 11, 15], target = 9; 因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer,Integer> map = new HashMap<>();
            for(int i = 0;i<nums.length;i++){
                int complement = target -nums[i];
                if (map.containsKey(nums[i]) && map.get(nums[i]) != i) {  
                    result[0] = map.get(nums[i]);
                    result[1] = i;
                    break;
            }
                map.put(complement,i);
     }
        return result;
    }
}
posted @ 2018-03-12 20:27  LegendQi  阅读(446)  评论(0编辑  收藏  举报