Question1(letecode)

Question:

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.

Example:

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

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

解决:

问题是要从数组中找到两个数据,使得两数之和等于目标值,输出该两数的下标(从0开始)。显而易见,这里最简单的是O(n^2)的时间复杂度的解决办法。

public static int[] twoSum(int[] nums, int target) {
    int[] answer = new int[2];
    A:for (int i = 0; i < nums.length; ++i){
        answer[0] = i;
        int b = target - nums[i];
        for (int j = i + 1; j < nums.length; ++j){
            if (nums[j] == b){
                answer[1] = j;
                break A;
            }
        }
    }
    return answer;
}

考虑O(n)的算法,可以使用map使得查找的复杂度降为O(1)

public int[] twoSum(int[] nums, int target) {
    int[] answer = new int[2];
    HashMap<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 b = target - nums[i];
        if (map.containsKey(b) && i != map.get(b))
            return new int[]{i, map.get(b)};
     }
     return answer;
}

猜你喜欢

转载自blog.csdn.net/weixin_41741008/article/details/88937115