两数之和II_LeetCode_167_1099
作者:互联网
LeetCode_167原题链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
LeetCode_1099原题链接:https://leetcode-cn.com/problems/two-sum-less-than-k/
package Leetcode;
import java.util.Arrays;
import java.util.Scanner;
/**
* @date 2022/4/3-18:47
* 给你一个下标从1开始的整数数组numbers,该数组已按非递减顺序排列,
* 请你从数组中找出满足相加之和等于目标数 target 的两个数。
*/
public class TwoSum_167 {
// 使用双指针,判断 两端和 与 target 的大小关系
public static int[] twoSum(int[] numbers, int target) {
int n = numbers.length;
int left = 0 ;
int right = n - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
return new int[] {left + 1, right + 1};
}
}
throw new IllegalArgumentException("No Solution");
}
public static void main(String[] args) {
// int[] numbers = {2, 7, 11, 15};
// int target = 9;
System.out.println("Please input array separated by space or commas");
Scanner in = new Scanner(System.in);
String str = in.next().toString();
String[] strArr = str.split(",");
int[] numbers = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
numbers[i] = Integer.parseInt(strArr[i]);
}
System.out.println(Arrays.toString(numbers));
System.out.println("Please input the value of target");
int target = in.nextInt();
in.close();
System.out.println(Arrays.toString(twoSum(numbers, target)));
}
}
leetCode_1099:给定的是无序数组A和一整数K,返回的是数组中的两个数的和尽可能接近整数K,但是不能取等号。
思路:跟上题一样,也是用双指针最方便,然后判断其和 与 整数K的大小关系。
注意:双指针使用前,必须有序,以及结果不存在时如何处理(定义初值)。
public int twoSumLessThanK(int[] A, int K) { if (A == null || A.length == 0) { return 0; } Arrays.sort(A); int left = 0; int right = A.length - 1; int res = Integer.MIN_VALUE; while (left < right) { int sum = A[left] + A[right]; if (sum < K) { res = Math.max(res, sum); left++; } else { right--; } } return res == Integer.MIN_VALUE ? -1 : res; }
标签:right,target,int,sum,II,numbers,167,两数,left 来源: https://www.cnblogs.com/pfzhang18/p/16097030.html