67. Two Sum II - Input array is sorted - LeetCode

Posted okokabcd

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了67. Two Sum II - Input array is sorted - LeetCode相关的知识,希望对你有一定的参考价值。

Question

167. Two Sum II - Input array is sorted

技术分享图片

Solution

题目大意:和Two Sum一样,这里给出的数组是有序的

思路:target - nums[i],这样就实现了降维了

Java实现:

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++) {
        if (map.containsKey(target - nums[i])) {
            result[1] = i + 1;
            result[0] = map.get(target - nums[i]) + 1;
            return result;
        }
        map.put(nums[i], i);
    }
    return result;
}

别人的实现:

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/discuss/51239/Share-my-java-AC-solution.

public int[] twoSum(int[] num, int target) {
    int[] indice = new int[2];
    if (num == null || num.length < 2) return indice;
    int left = 0, right = num.length - 1;
    while (left < right) {
        int v = num[left] + num[right];
        if (v == target) {
            indice[0] = left + 1;
            indice[1] = right + 1;
            break;
        } else if (v > target) {
            right --;
        } else {
            left ++;
        }
    }
    return indice;
}

以上是关于67. Two Sum II - Input array is sorted - LeetCode的主要内容,如果未能解决你的问题,请参考以下文章

167. Two Sum II - Input array is sorted

LeetCode Two Sum II - Input array is sorted

167. Two Sum II - Input array is sorted

167. Two Sum II - Input array is sorted

LeetCode167. Two Sum II - Input array is sorted

[LeetCode] 167. Two Sum II - Input array is sorted