【LeetCode】Two Sum II - Input array is sorted

2023-06-14,,

【Description】

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.

【AC code】

一、暴力法  时间复杂度:O(n^2)

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

二、二分查找法  时间复杂度:O(nlogn)

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

三、双索引法  时间复杂度:O(n)

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

【LeetCode】Two Sum II - Input array is sorted的相关教程结束。

《【LeetCode】Two Sum II - Input array is sorted.doc》

下载本文的Word格式文档,以方便收藏与打印。