LeetCode 16 3Sum Closest(最接近的3个数的和)
生活随笔
收集整理的這篇文章主要介紹了
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)度len,current之所以要小于len?2,是因?yàn)楹竺嫘枰魞蓚€(gè)位置給front和back
始終保證front小于back
計(jì)算索引為current、front、back的數(shù)的和,分別有比target更小、更大、相等三種情況
更小:如果距離小于close,那么close便等于target?sum,而結(jié)果就是sum。更大的情況同理
如果相等,那么要記得將0賦值給close,result就直接等于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)題。
- 上一篇: 梦到自己溺水是什么意思
- 下一篇: 条款46:需要类型转换的时候请为模板定义