One LeetCode per day (37): The sum of two numbers II-Input an ordered array

3 minutes a day, embark on the path of algorithm counterattack.

Collection of previous articles

A collection of LeetCode previous articles every day

Code warehouse

GitHub: https://github.com/meteor1993/LeetCode

Gitee : https://gitee.com/inwsy/LeetCode

Topic: Sum of Two Numbers II-Input an ordered array

Question source: https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/

Given an ordered array that has been arranged in ascending order, find two numbers so that their sum is equal to the target number.

The function should return the two subscript values ​​index1 and index2, where index1 must be less than index2.

Description:

  • The returned subscript values ​​(index1 and index2) are not zero-based.
  • You can assume that each input only corresponds to a unique answer, and you cannot reuse the same elements.

Example:

输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。

Option 1: Violence Law

If I remember this question correctly, it should be a deformation of the first question I did. Those who have read my article said that I would not do it myself to find a place to circle.

The simplest idea is violent iteration. The time complexity is O(n^2) and the space complexity is O(1). The code is extremely simple. Just two loops are combined with violence.

public int[] twoSum(int[] numbers, int target) {
    
    
    for (int i = 0; i < numbers.length; i++) {
    
    
        for (int j = i + 1; j < numbers.length; j++) {
    
    
            if (target - numbers[i] == numbers[j]) {
    
    
                return new int[] {
    
    i + 1, j + 1};
            }
        }
    }
    return null;
}

Except that it takes a lot of time, there is nothing wrong with it.

Option 2: Hash table

The above brute force method takes too much time to find the second number. We can find the second number with the help of a hash table in a loop.

// 哈希表
public int[] twoSum_1(int[] numbers, int target) {
    
    
    Map<Integer, Integer> map = new HashMap<>(numbers.length);
    for (int i = 0; i < numbers.length; i++) {
    
    
        if (map.containsKey(target - numbers[i])) {
    
    
            return new int[] {
    
    map.get(target - numbers[i]) + 1, i + 1};
        }
        map.put(numbers[i], i);
    }
    return null;
}

This plan took a short time to come down, but only beat 36.12% of the people, indicating that there must be a better plan.

Option 3: Dichotomy

I won’t explain much about this plan, as I know from the name, it’s a plan that takes half from the middle.

// 二分法
public int[] twoSum(int[] numbers, int target) {
    
    
    for (int i = 0; i < numbers.length; i++) {
    
    
        int low = i + 1, high = numbers.length - 1;
        while (low <= high) {
    
    
            int mid = (high - low) / 2 + low;
            if (numbers[mid] == target - numbers[i]) {
    
    
                return new int[] {
    
    i + 1, mid + 1};
            } else if (numbers[mid] > target - numbers[i]){
    
    
                high = mid - 1;
            } else {
    
    
                low = mid + 1;
            }
        }
    }
    return null;
}

It seems that the dichotomy is not as fast as the above hash table.

Option 4: Double pointer

As the name implies, double pointers are two pointers, one moving from front to back, and one moving from back to forward. This scheme is based entirely on the current order of an array.

// 双指针
public int[] twoSum_3(int[] numbers, int target) {
    
    
    int left  = 0, right = numbers.length - 1;
    while (left < right) {
    
    
        int sum = numbers[left] + numbers[right];
        if (target == sum) {
    
    
            return new int[] {
    
    left + 1, right + 1};
        } else if (sum < target){
    
    
            ++left;
        } else {
    
    
            --right;
        }
    }
    return null;
}

This scheme is completely based on an ordered array. If it is unordered, it cannot be used. The worst case is that the time complexity is O(n). The entire array is looped again. As long as it is not the worst, it will be better than O(n). .

Your scan code attention is the biggest encouragement for the editor to insist on originality:)

Guess you like

Origin blog.csdn.net/meteor_93/article/details/108415535