跳转至

剑指 Offer II 006. 排序数组中两个数字之和

题目描述

给定一个已按照 升序排列  的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target

函数应该以长度为 2 的整数数组的形式返回这两个数的下标值numbers 的下标 从 0 开始计数 ,所以答案数组应当满足 0 <= answer[0] < answer[1] < numbers.length 。

假设数组中存在且只存在一对符合条件的数字,同时一个数字不能使用两次。

 

示例 1:

输入:numbers = [1,2,4,6,10], target = 8
输出:[1,3]
解释:2 与 6 之和等于目标数 8 。因此 index1 = 1, index2 = 3 。

示例 2:

输入:numbers = [2,3,4], target = 6
输出:[0,2]

示例 3:

输入:numbers = [-1,0], target = -1
输出:[0,1]

 

提示:

  • 2 <= numbers.length <= 3 * 104
  • -1000 <= numbers[i] <= 1000
  • numbers递增顺序 排列
  • -1000 <= target <= 1000
  • 仅存在一个有效答案

 

注意:本题与主站 167 题相似(下标起点不同):https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/

解法

方法一:二分查找

我们注意到数组按照非递减顺序排列,因此对于每个 $numbers[i]$,可以通过二分查找的方式找到 $target - numbers[i]$ 的位置,如果存在,那么返回 $[i, j]$ 即可。

时间复杂度 $O(n \times \log n)$,其中 $n$ 为数组 $numbers$ 的长度。空间复杂度 $O(1)$。

1
2
3
4
5
6
7
8
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_left(numbers, x, lo=i + 1)
            if j < n and numbers[j] == x:
                return [i, j]
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        for (int i = 0, n = numbers.length;; ++i) {
            int x = target - numbers[i];
            int l = i + 1, r = n - 1;
            while (l < r) {
                int mid = (l + r) >> 1;
                if (numbers[mid] >= x) {
                    r = mid;
                } else {
                    l = mid + 1;
                }
            }
            if (numbers[l] == x) {
                return new int[] {i, l};
            }
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        for (int i = 0, n = numbers.size();; ++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, j};
            }
        }
    }
};
1
2
3
4
5
6
7
8
9
func twoSum(numbers []int, target int) []int {
    for i, n := 0, len(numbers); ; i++ {
        x := target - numbers[i]
        j := sort.SearchInts(numbers[i+1:], x) + i + 1
        if j < n && numbers[j] == x {
            return []int{i, j}
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function twoSum(numbers: number[], target: number): number[] {
    const n = numbers.length;
    for (let i = 0; ; ++i) {
        const x = target - numbers[i];
        let l = i + 1;
        let r = n - 1;
        while (l < r) {
            const mid = (l + r) >> 1;
            if (numbers[mid] >= x) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        if (numbers[l] === x) {
            return [i, l];
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 target.cmp(&(numbers[l] + numbers[r])) {
                Ordering::Less => {
                    r -= 1;
                }
                Ordering::Greater => {
                    l += 1;
                }
                Ordering::Equal => {
                    break;
                }
            }
        }
        vec![l as i32, r as i32]
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
        let n = numbers.count
        for i in 0..<n {
            let x = target - numbers[i]
            var l = i + 1
            var r = n - 1
            while l < r {
                let mid = (l + r) / 2
                if numbers[mid] >= x {
                    r = mid
                } else {
                    l = mid + 1
                }
            }
            if l < n && numbers[l] == x {
                return [i, l]
            }
        }
        return []
    }
}

方法二:双指针

我们定义两个指针 $i$ 和 $j$,分别指向数组的第一个元素和最后一个元素。每次计算 $numbers[i] + numbers[j]$,如果和等于目标值,那么返回 $[i, j]$ 即可。如果和小于目标值,那么将 $i$ 右移一位,如果和大于目标值,那么将 $j$ 左移一位。

时间复杂度 $O(n)$,其中 $n$ 为数组 $numbers$ 的长度。空间复杂度 $O(1)$。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        i, j = 0, len(numbers) - 1
        while i < j:
            x = numbers[i] + numbers[j]
            if x == target:
                return [i, j]
            if x < target:
                i += 1
            else:
                j -= 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        for (int i = 0, j = numbers.length - 1;;) {
            int x = numbers[i] + numbers[j];
            if (x == target) {
                return new int[] {i, j};
            }
            if (x < target) {
                ++i;
            } else {
                --j;
            }
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        for (int i = 0, j = numbers.size() - 1;;) {
            int x = numbers[i] + numbers[j];
            if (x == target) {
                return {i, j};
            }
            if (x < target) {
                ++i;
            } else {
                --j;
            }
        }
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
func twoSum(numbers []int, target int) []int {
    for i, j := 0, len(numbers)-1; ; {
        x := numbers[i] + numbers[j]
        if x == target {
            return []int{i, j}
        }
        if x < target {
            i++
        } else {
            j--
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function twoSum(numbers: number[], target: number): number[] {
    for (let i = 0, j = numbers.length - 1; ; ) {
        const x = numbers[i] + numbers[j];
        if (x === target) {
            return [i, j];
        }
        if (x < target) {
            ++i;
        } else {
            --j;
        }
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
use std::cmp::Ordering;

impl Solution {
    pub fn two_sum(numbers: Vec<i32>, target: i32) -> Vec<i32> {
        let n = numbers.len();
        for i in 0..n - 1 {
            let num = target - numbers[i];
            let mut l = i + 1;
            let mut r = n - 1;
            while l <= r {
                let mid = l + (r - l) / 2;
                match num.cmp(&numbers[mid]) {
                    Ordering::Less => {
                        r = mid - 1;
                    }
                    Ordering::Greater => {
                        l = mid + 1;
                    }
                    Ordering::Equal => {
                        return vec![i as i32, mid as i32];
                    }
                }
            }
        }
        vec![-1, -1]
    }
}

评论