Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .
Sum of Two Numbers II - Input Sorted Array
Given an integer array with subscripts starting from 1numbers
, the array has been arranged in non- decreasing order , please find two numbers from the array that satisfy the addition and the sum is equal to the target target
number. If these two numbers are respectively numbers[index1]
and numbers[index2]
, then 1 <= index1 < index2 <= numbers.length
.
Returns the sum of the subscripts of these two integers as an array of of length 2 .[index1, index2]
index1
index2
You can assume that each corresponds to a unique answer , and you cannot reuse the same elements.
The solution you design must use only constant-level extra space. Example 1:
输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
复制代码
Example 2:
输入:numbers = [2,3,4], target = 6
输出:[1,3]
解释:2 与 4 之和等于目标数 6 。因此 index1 = 1, index2 = 3 。返回 [1, 3] 。
复制代码
Example 3:
输入:numbers = [-1,0], target = -1
输出:[1,2]
解释:-1 与 0 之和等于目标数 -1 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。
复制代码
Thought analysis
method one
Simple and rude double-layer loop, judge the condition, and then return to the subscript.
Method Two
- Because the array is ordered, binary search can be used.
- To find the sum of two numbers equal to the target value, you can fix one number first, then find another number, and the other number is equal to the target value minus the first number.
- The left boundary, right boundary and median are still defined, and the circular movement can be obtained.
AC code
method one
/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
var twoSum = function(numbers, target) {
const len = numbers.length
for(let i = 0; i < len; i++) {
for(let j = i + 1; j < len; j++) {
if(numbers[i] + numbers[j] === target) {
return [i + 1, j + 1]
}
}
}
};
复制代码
result:
- Execution result: passed
- Execution time: 548 ms, beating 5.06% of users across all JavaScript commits
- Memory consumption: 42 MB, beats 44.43% of users across all JavaScript submissions
- Test cases passed: 21/21
Method Two
/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
var twoSum = function(numbers, target) {
for (let i = 0; i < numbers.length; i++) {
let low = i + 1
let high = numbers.length - 1
while (low <= high) {
let mid = Math.floor((high - low) / 2) + low;
if (numbers[mid] === target - numbers[i]) {
return [i + 1, mid + 1];
} else if (numbers[mid] > target - numbers[i]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
}
};
复制代码
result:
- Execution result: passed
- Execution time: 64 ms, beating 81.18% of users across all JavaScript submissions
- Memory consumption: 42.3 MB, beats 17.11% of users across all JavaScript submissions
- Test cases passed: 21/21