TwoSum

给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。

您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。

例子:

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

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

我的解决方法:

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

LeetCode解决方法:

方法一:暴力相加

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

方法二:双程哈希表

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

方法三:单程哈希表

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}
posted @ 2017-10-12 09:13  K_artorias  阅读(224)  评论(0编辑  收藏  举报