日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 16 3Sum Closest(最接近的3个数的和)

發(fā)布時(shí)間:2023/11/29 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 16 3Sum Closest(最接近的3个数的和) 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

翻譯

給定一個(gè)有n個(gè)整數(shù)的數(shù)組S,找出S中3個(gè)數(shù),使其和等于一個(gè)給定的數(shù),target。返回這3個(gè)數(shù)的和,你可以假定每個(gè)輸入都有且只有一個(gè)結(jié)果。例如,給定S = {-1 2 1 -4},和target = 1。那么最接近target的和是2。(-1 + 2 + 1 = 2)。

原文

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.For example, given array S = {-1 2 1 -4}, and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

思考

也許我已經(jīng)開始體會(huì)到上一題中別人寫的方法的思想了。

在這個(gè)題目中,我們要做以下幾件事:

  • sort對(duì)輸入的數(shù)組進(jìn)行排序

  • 求出長(zhǎng)度lencurrent之所以要小于len?2,是因?yàn)楹竺嫘枰魞蓚€(gè)位置給frontback

  • 始終保證front小于back

  • 計(jì)算索引為current、front、back的數(shù)的和,分別有比target更小、更大、相等三種情況

  • 更小:如果距離小于close,那么close便等于target?sum,而結(jié)果就是sum。更大的情況同理

  • 如果相等,那么要記得將0賦值給closeresult就直接等于target

  • 隨后為了避免計(jì)算重復(fù)的數(shù)字,用三個(gè)do/while循環(huán)遞增或遞減它們

代碼

class Solution { public:int threeSumClosest(vector<int>& nums, int target) {sort(nums.begin(), nums.end());int len = nums.size();int result = INT_MAX, close = INT_MAX;for (int current = 0; current < len - 2; current++) {int front = current + 1, back = len - 1;while (front < back) {int sum = nums[current] + nums[front] + nums[back];if (sum < target) {if (target - sum < close) {close = target - sum;result = sum;}front++;}else if (sum > target) {if (sum - target < close) {close = sum - target;result = sum;}back--;}else {close = 0;result = target;do {front++;} while (front < back&&nums[front - 1] == nums[front]);do {back--;} while (front < back&&nums[back + 1] == nums[back]);}}while (current < len - 2 && nums[current + 1] == nums[current]) {current++;}} return result;} };

和本道題關(guān)聯(lián)密切的題目推薦:

傳送門:LeetCode 15 3Sum(3個(gè)數(shù)的和)
傳送門:LeetCode 18 4Sum(4個(gè)數(shù)的和)

總結(jié)

以上是生活随笔為你收集整理的LeetCode 16 3Sum Closest(最接近的3个数的和)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。