摘要:返回這三個值的和。思路一三指針這里的思路和是一樣的,就是用三個指針獲得三個值并計算他們的和。
題外話
鑒于這一題的核心思路和leetcode15的思路相同,可以先寫一下15題并參考一下我之前的一篇博客
題目要求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).
翻譯過來就是,假設(shè)一個有n的元素的整數(shù)數(shù)組S,從S中找到三個值,這三個值的距離輸入的目標值最近。返回這三個值的和。
思路一:三指針這里的思路和leetcode15是一樣的,就是用三個指針獲得三個值并計算他們的和。不同的是和當前的最小距離比較,代碼如下
public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int length = nums.length; int closest = nums[0]+nums[1]+nums[2] - target; for(int i = 0 ; i思路二:hashmap等0){ while(nums[k--] == nums[k] && j < k); } if(value==0){ return target; } if(Math.abs(value) < Math.abs(closest)){ closest = value; } } while(nums[i] == nums[++i] && i < nums.length - 2); } return closest + target; }
同leetcode15,請直接參考我的博客
想要了解更多開發(fā)技術(shù),面試教程以及互聯(lián)網(wǎng)公司內(nèi)推,歡迎關(guān)注我的微信公眾號!將會不定期的發(fā)放福利哦~
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/67013.html
摘要:題目詳情給定一個整數(shù)數(shù)組,我們需要找出數(shù)組中三個元素的加和,使這個加和最接近于輸入的數(shù)值。返回這個最接近的加和。找后兩個元素的時候,使用左右指針從兩端查找。 題目詳情 Given an array S of n integers, find three integers in S such that the sum is closest to a given number, targe...
摘要:這個題和的做法基本一樣,只要在循環(huán)內(nèi)計算和最接近的和,并賦值更新返回值即可。 Problem 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 intege...
摘要:為了避免得到重復結(jié)果,我們不僅要跳過重復元素,而且要保證找的范圍要是在我們最先選定的那個數(shù)之后的。而計算則同樣是先選一個數(shù),然后再剩下的數(shù)中計算。 2Sum 在分析多數(shù)和之前,請先看Two Sum的詳解 3Sum 請參閱:https://yanjia.me/zh/2019/01/... 雙指針法 復雜度 時間 O(N^2) 空間 O(1) 思路 3Sum其實可以轉(zhuǎn)化成一個2Sum的題,...
摘要:前言從開始寫相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當時也沒有按順序?qū)懍F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖?。所以在這里做個索引嘻嘻。順序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 從開始寫leetcode相關(guān)的博客到現(xiàn)在也蠻多篇了。而且當時也沒有按順序?qū)憽F(xiàn)在翻起來覺得蠻亂的??赡艽蠹铱粗卜浅2环奖恪K栽谶@里做個索引嘻嘻。 順序整理 1~50 1...
摘要:找符合條件的總數(shù)。雙指針區(qū)間考慮邊界,長度,為空,等。之后的范圍用雙指針和表示。若三個指針的數(shù)字之和為,加入結(jié)果數(shù)組。不要求,所以不用判斷了。同理,頭部兩個指針向后推移,后面建立左右指針夾逼,找到四指針和為目標值的元素。 Two Sum Problem Given an array of integers, find two numbers such that they add up ...
閱讀 2116·2021-11-24 09:39
閱讀 1602·2021-10-11 10:59
閱讀 2533·2021-09-24 10:28
閱讀 3409·2021-09-08 09:45
閱讀 1298·2021-09-07 10:06
閱讀 1699·2019-08-30 15:53
閱讀 2105·2019-08-30 15:53
閱讀 1443·2019-08-30 15:53