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;
}

猜你喜欢

转载自www.cnblogs.com/okokabcd/p/9489532.html