167. 两数之和 II - 输入有序数组
2021-04-12 21:28
标签:bsp twosum 解法 返回 static == arrays 元素 不可 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。 函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。 说明: 示例: 167. 两数之和 II - 输入有序数组 标签:bsp twosum 解法 返回 static == arrays 元素 不可 原文地址:https://www.cnblogs.com/TripL/p/13347839.html
输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]
解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
public class TwoSum {
//暴力解法
public static int[] twoSumV1(int[] numbers, int target) {
int[] result = new int[2];
if (numbers.length ) {
return result;
}
int temp;
for (int i = 0; i ) {
temp = numbers[i];
if (temp target) {
for (int j = i + 1; j ) {
if (temp + numbers[j] == target) {
result[0] = i + 1;
result[1] = j + 1;
}
}
}
}
return result;
}
//二分法
public static int[] twoSumV2(int[] numbers, int target) {
for (int i = 0; i ) {
if (numbers[i] target) {
int left = i + 1;
int right = numbers.length - 1;
//二分法查找temp值
while (left right) {
int middle = (right - left) / 2 + left;
if (numbers[middle] > target - numbers[i]) {
right = middle - 1;
} else if (numbers[middle] numbers[i]) {
left = middle + 1;
} else {
return new int[]{i + 1, middle + 1};
}
}
}
}
return new int[]{-1, -1};
}
//双指针
public static int[] twoSumV3(int[] numbers, int target) {
int startIndex = 0;
int endIndex = numbers.length - 1;
while (startIndex endIndex) {
int temp = numbers[startIndex] + numbers[endIndex];
if (temp > target) {
--endIndex;
} else if (temp target) {
++startIndex;
} else {
return new int[]{startIndex + 1, endIndex + 1};
}
}
return new int[]{-1, -1};
}
public static void main(String[] args) {
int[] numbers = {-1, 0};
int[] ints = twoSumV3(numbers, -1);
System.out.println(Arrays.toString(ints));
}
}
文章标题:167. 两数之和 II - 输入有序数组
文章链接:http://soscw.com/index.php/essay/74899.html