leetcode-16-最接近的三数之和
生活随笔
收集整理的這篇文章主要介紹了
leetcode-16-最接近的三数之和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題:
?
解:
package com.example.demo;import java.util.Arrays;public class Test16 {/*** 給定一個包括 n 個整數的數組 nums 和 一個目標值 target。找出 nums 中的三個整數,* 使得它們的和與 target 最接近。返回這三個數的和。假定每組輸入只存在唯一答案。** @param nums* @param target* @return*/public int threeSumClosest(int[] nums, int target) {/*排序+雙指針先使用排序,將nums數據排好,讓后定義兩個指針,分別指向當前位置的下一個和最后一個數字,然后將三個數的和 跟target比較*/Arrays.sort(nums);int res = nums[0] + nums[1] + nums[2];for (int i = 0; i < nums.length; i++) {int left = i + 1;int right = nums.length - 1;while (left < right) {int sum = nums[i] + nums[left] + nums[right];if (Math.abs(target - sum) < Math.abs(target - res)) {res = sum;}if (sum > target) {right--;} else if (sum < target) {left++;} else {return res;}}}return res;}public static void main(String[] args) {Test16 t = new Test16();int[] arr = {0, 2, 1, -3};int i = t.threeSumClosest(arr, 1);System.out.println(i);} }?
總結
以上是生活随笔為你收集整理的leetcode-16-最接近的三数之和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode-26-删除排序数组中的
- 下一篇: leetcode-14-最长公共前缀