两数之和II_LeetCode_167_1099
2022/4/3 23:22:35
本文主要是介绍两数之和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; }
这篇关于两数之和II_LeetCode_167_1099的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升