两数之和

给定整数数组,如果有两个数之和是给定的数,那么返回两个数的下标。

每组输入只有一个解,同一个数不能用两次

例如:给定nums=[2,7,11,15],target=9,

因为nums[0]+nums[1]=9

返回[0,1]

我的答案:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        for(int i = 0;i<nums.length;i++){
            for(int j = 0;j<nums.length;j++){
                if(nums[i]+nums[j]==target){
                    if(i==j)continue;
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;
    }
}

看了别人优秀的答案:

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                result[1] = i;
                result[0] = map.get(target - nums[i])-1;
                return result;
            }
        map.put(nums[i], i+1);
        }
    return result;
    }
}

使用HashMap,使的效率更高。

posted @ 2017-04-05 22:33  alittlecomputer  阅读(197)  评论(0编辑  收藏  举报