Leetcode No.167 two sum II – input array is sorted (c + + implementation)

Time:2021-12-21

1. Title

1.1 English title

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

Return the indices of the two numbers (1-indexed) as an integer array answer of size 2, where 1 <= answer[0] < answer[1] <= numbers.length.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

1.2 Chinese title

An ordered array to find the position where the sum of two numbers is equal to a specific number.
Note: the index starts with 1 and an element in the array can only be used once.

1.3 input and output

input output
numbers = [2,7,11,15], target = 9 [1,2]
numbers = [2,3,4], target = 6 [1,3]
numbers = [-1,0], target = -1 [1,2]

1.4 constraints

  • 2 <= numbers.length <= 3 * 104
  • -1000 <= numbers[i] <= 1000
  • numbers is sorted in non-decreasing order.
  • -1000 <= target <= 1000
  • The tests are generated such that there is exactly one solution.

2. Analysis

2.1 violence solving method

This problem can first use the violence solving method to traverse all possible combinations, with a complexity of O(\(n^{2}\)), the code is as follows:

class Solution {
public:
    vector twoSum(vector& numbers, int target) {
        vector result(2);
        for (int i = 0; i < numbers.size() - 1; i++)
        {
            for (int j = i + 1; j < numbers.size(); j++)
            {
                if (target - numbers[i] == numbers[j])
                {
                    result = { ++i, ++j };
                    break;
                }
            }
        }
        return result;
    }
};

This method is inefficient and does not take advantage of the condition of array ordering

2.2 Hash table method

This method refers to the solution of the first problem of leetcode. The only difference between the first problem and this problem is that the array of the first problem is disordered. Therefore, the hash table method of the first problem is also applicable to this problem, but it does not take advantage of the condition of array order, which is non optimal, and the time complexity is O (n). The code is as follows:

class Solution {
public:
    vector twoSum(vector& numbers, int target) {
		//Hash table
        map hashMap;
        vector ans;
        int temp = 0;
        for (int i = 0; i < numbers.size(); i++)
        {
            temp = target - numbers[i];
            if (hashMap.count(temp))
            {
                ans = { ++hashMap[temp], ++i };
                break;
            }
            hashMap[numbers[i]] = i;
        }
        return ans;
    }
};

2.3 dichotomy

Traverse one to find another, and the array is orderly. It’s easy to think of dichotomy, with a time complexity of O(\(nlogn\))。 The specific codes are as follows:

class Solution {
public:
    vector twoSum(vector& numbers, int target) {
		//Dichotomy
        vector result;
        for (int i = 0; i < numbers.size() - 1; i++)
        {
            int second = target - numbers[i];
            int left = i + 1;
            int right = numbers.size() - 1;
            while (left <= right)
            {
                int mid = (left + right) / 2;
                if (second < numbers[mid])
                    right = mid - 1;
                else if (second > numbers[mid])
                    left = mid + 1;
                else
                {
                    result.push_back(++i);
                    result.push_back(++mid);
                    break;
                }
                if (result.size() == 2)
                    break;
            }
        }
        return result;
    }
};

2.4 head and tail pointer method

This method uses two pointers to point to the head and tail respectively, and compares the sum of the head and tail and the target number. If the former is large, the tail pointer moves left, and if the former is small, the pointer moves right. The time complexity is O (n), and the code is as follows:

public:
    vector twoSum(vector& numbers, int target) {
        vector result;
        int head = 0;
        int tail = numbers.size() - 1;
        while (head < tail)
        {
            int tempAdd = numbers[head] + numbers[tail];
            if (tempAdd < target)
                head++;
            else if (tempAdd > target)
                tail--;
            else
            {
                result = { ++head, ++tail };
                break;
            }  
        }
        return result;
    }
};

reference resources:https://www.jianshu.com/p/f3a8a247f4c8

Recommended Today

IOS overall framework and class inheritance framework diagram

I. overall framework In the process of IOS development, understanding and learning the overall framework of IOS is an essential link. Today, let’s have a good understanding of the overall framework of IOS. First, post a framework introduction about IOS:Overview of IOS system framework。 We usually call the IOS framework cocoa touch framework. Cocoa touch […]