Loading

1. Two Sum

Description


Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解法1:最直观的暴力破解法,用时94ms,优点是省空间,缺点是费时。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length < 2) {
            return null;
        }
        int[] r = 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) && (i != j)) {
                    r[0] = i;
                    r[1] = j;
                    return r;
                }
            }
        }
        return null;
    }
}

解法二:使用一个额外的map来作为辅助,只需遍历一次,用时4ms,优点是省时间,缺点是费空间。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        if(nums.length < 2) {
            return null;
        }
        int[] r = new int[2];
        Map<Integer,Integer> helper = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            if(helper.containsKey(target - nums[i])) {
                r[0] = helper.get(target - nums[i]);
                r[1] = i;
                return r;
            } else {
                helper.put(nums[i], i);
            }
        }
        return null;
    }
}
posted @ 2018-07-09 13:41  CodeTiger  阅读(17)  评论(0编辑  收藏  举报