Skip to content

Latest commit

 

History

History
351 lines (298 loc) · 8.28 KB

File metadata and controls

351 lines (298 loc) · 8.28 KB

中文文档

Description

Given a 1-indexed 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. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

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

Your solution must use only constant extra space.

 

Example 1:

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. We return [1, 2].

Example 2:

Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].

Example 3:

Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].

 

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.

Solutions

Python3

Binary search:

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        n = len(numbers)
        for i in range(n - 1):
            x = target - numbers[i]
            j = bisect.bisect_left(numbers, x, lo=i + 1)
            if j != n and numbers[j] == x:
                return [i + 1, j + 1]
        return [-1, -1]

Two pointers:

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i, j = 1, len(numbers)
        while i < j:
            x = numbers[i - 1] + numbers[j - 1]
            if x == target:
                return [i, j]
            if x < target:
                i += 1
            else:
                j -= 1
        return [-1, -1]

Java

Binary search:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        for (int i = 0, n = numbers.length; i < n - 1; ++i) {
            int x = target - numbers[i];
            int left = i + 1, right = n - 1;
            while (left < right) {
                int mid = (left + right) >> 1;
                if (numbers[mid] >= x) {
                    right = mid;
                } else {
                    left = mid + 1;
                }
            }
            if (numbers[left] == x) {
                return new int[]{i + 1, left + 1};
            }
        }
        return new int[]{-1, -1};
    }
}

Two pointers:

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int i = 1, j = numbers.length;
        while (i < j) {
            int x = numbers[i - 1] + numbers[j - 1];
            if (x == target) {
                return new int[] {i, j};
            }
            if (x < target) {
                ++i;
            } else {
                --j;
            }
        }
        return new int[] {-1, -1};
    }
}

TypeScript

Binary search:

function twoSum(numbers: number[], target: number): number[] {
    for (let i = 0, n = numbers.length; i < n - 1; ++i) {
        const x = target - numbers[i];
        let left = i + 1,
            right = n - 1;
        while (left < right) {
            const mid = (left + right) >> 1;
            if (numbers[mid] >= x) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        if (numbers[left] == x) {
            return [i + 1, left + 1];
        }
    }
    return [-1, -1];
}

Two pointers:

function twoSum(numbers: number[], target: number): number[] {
    let i = 1,
        j = numbers.length;
    while (i < j) {
        const x = numbers[i - 1] + numbers[j - 1];
        if (x == target) {
            return [i, j];
        }
        if (x < target) {
            ++i;
        } else {
            --j;
        }
    }
    return [-1, -1];
}

C++

Binary search:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        for (int i = 0, n = numbers.size(); i < n - 1; ++i) {
            int x = target - numbers[i];
            int j = lower_bound(numbers.begin() + i + 1, numbers.end(), x) - numbers.begin();
            if (j != n && numbers[j] == x) return {i + 1, j + 1};
        }
        return {-1, -1};
    }
};

Two pointers:

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int i = 1, j = numbers.size();
        while (i < j)
        {
            int x = numbers[i - 1] + numbers[j - 1];
            if (x == target) return {i, j};
            if (x < target) ++i;
            else --j;
        }
        return {-1, -1};
    }
};

Go

Binary search:

func twoSum(numbers []int, target int) []int {
	for i, n := 0, len(numbers); i < n-1; i++ {
		x := target - numbers[i]
		left, right := i+1, n-1
		for left < right {
			mid := (left + right) >> 1
			if numbers[mid] >= x {
				right = mid
			} else {
				left = mid + 1
			}
		}
		if numbers[left] == x {
			return []int{i + 1, left + 1}
		}
	}
	return []int{-1, -1}
}

Two pointers:

func twoSum(numbers []int, target int) []int {
	i, j := 1, len(numbers)
	for i < j {
		x := numbers[i-1] + numbers[j-1]
		if x == target {
			return []int{i, j}
		}
		if x < target {
			i++
		} else {
			j--
		}
	}
	return []int{-1, -1}
}

JavaScript

Binary search:

/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (numbers, target) {
    for (let i = 0, n = numbers.length; i < n - 1; ++i) {
        const x = target - numbers[i];
        let left = i + 1,
            right = n - 1;
        while (left < right) {
            const mid = (left + right) >> 1;
            if (numbers[mid] >= x) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        if (numbers[left] == x) {
            return [i + 1, left + 1];
        }
    }
    return [-1, -1];
};

Two pointers:

/**
 * @param {number[]} numbers
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (numbers, target) {
    let i = 1,
        j = numbers.length;
    while (i < j) {
        const x = numbers[i - 1] + numbers[j - 1];
        if (x == target) {
            return [i, j];
        }
        if (x < target) {
            ++i;
        } else {
            --j;
        }
    }
    return [-1, -1];
};

Rust

use std::cmp::Ordering;

impl Solution {
    pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
        let n = numbers.len();
        let mut l = 0;
        let mut r = n - 1;
        loop {
            match (numbers[l] + numbers[r]).cmp(&target) {
                Ordering::Less => l += 1,
                Ordering::Greater => r -= 1,
                Ordering::Equal => break,
            }
        }
        vec![l as i32 + 1, r as i32 + 1]
    }
}

...