1. 程式人生 > >LeetCode刷題EASY篇Two Sum II - Input array is sorted

LeetCode刷題EASY篇Two Sum II - Input array is sorted

題目

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

 

我的思路

首先遍歷,存入map,第二次遍歷,判斷target-current value 元素是否在map中,在,返回索引。

之前有two sum的題目,陣列是無序的,我原來也是採用這個思路,但是可以優化,不需要遍歷兩次,一次就夠,看下面的程式碼

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

這個思路肯定可行,但是無法利用有序這個特點,應該不是最優解法。

利用兩個指標遍歷,根據當前sum決定指標的移動情況,測試通過,但是隻是超過了1%

的提交,時間複雜度太高。

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        int p = 0;
        int q = 1;
         while (p < nums.length || q < nums.length) {
            if (q > nums.length - 1) {
                p++;
                q = p + 1;
            }
            int sum = nums[p] + nums[q];
            if (sum < target) {
                q++;
            }
            if (sum == target) {
                res[0] = p + 1;
                res[1] = q + 1;
                return res;
            }
            if (sum > target) {
                p++;
                q = p + 1;
            }


        }
        return res;
    }
}

優化解法

兩個指標沒有錯,應該從兩頭開始。這樣效率就會高很多,看了其他人的思路,修改一下:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        int p = 0;
        int q = nums.length-1;
         while (p < q) {
            int sum = nums[p] + nums[q];
            if (sum < target) {
                p++;
            }
            if (sum == target) {
                res[0] = p + 1;
                res[1] = q + 1;
                return res;
            }
            if (sum > target) {
                q--;
            }


        }
        return res;
    }
}