1. 程式人生 > >3Sum Closest ——解題報告

3Sum Closest ——解題報告

    【題目】

    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).

    【分析】

    這道題目與尋找和為定值的3個數類似。

    遍歷a,然後需要最接近target-a的兩個數b和c。這個子問題可以用two pointers的思路來做。記住,如果a+b+c正好等於target,直接返回target。如果不等,才需要把較大還是較小分情況討論。

    【程式碼】

     執行時間:17ms

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        if(nums.size() < 3)
            return 0;
            
        sort(nums.begin(), nums.end());
        int res = nums[0] + nums[1] + nums[2];
        for(int i = 0; i < nums.size() - 2; i++)
        {
            int lo = i + 1; 
            int hi = nums.size() - 1; 
            while(lo < hi)
            {
                int sum = nums[i] + nums[lo] + nums[hi];
                int diff1 = (sum - target > 0) ? (sum - target) : (target - sum);  // the non-negative difference
                int diff2 = (res - target > 0) ? (res - target) : (target - res);
                res = diff1 < diff2 ? sum : res; // res corresponding to the minimal diff
                if(diff1 == 0)
                    return res;
                else if(sum < target)
                    lo++;
                else
                    hi--;
            }
        }
        return res;
    }
};


相關推薦

3Sum Closest解題報告

題目 Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target.

【LeetCode】3Sum Closest 解題報告

【題目】 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

3Sum Closest ——解題報告

    【題目】     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

LeetCode解題報告--3Sum Closest

題目:與3數和最接近的和 Given an array S of n integers, find three integers in S such that the sum is closest t

【LeetCode】3Sum 解題報告

這道題憑我現有知識實在解答不上來,只好網上搜索解法,才發現 K Sum 是一類問題,但是網上沒有比較簡潔的程式碼,我想對於初學者來說,可能還是想先看看這道題怎麼解,然後才有興趣去看其擴充套件吧。 【題目】 Given an array S of n integers,

【LeetCode】15. 3Sum 解題報告(Python)

題目描述: Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in

3Sum——解題報告

    【題目】      Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the a

LeetCoder 解題報告 3Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which g

【LeetCode】849. Maximize Distance to Closest Person 解題報告(Python)

目錄題目描述題目大意解題方法日期 題目描述 In a row of seats, 1 represents a person sitting in that seat, and 0 represents that the seat is empty. Th

網易2017秋招編程題——回文序列 解題報告

out += stream pan 唯一性 [1] bsp names length Problem:https://www.nowcoder.com/question/next?pid=2811407&qid=46573&tid=6015849 如果一個數

解題報告 之 HDU5288 OO&#39; s Sequence

bold repr frame roman efi int tom relative 記錄 解題報告 之 HDU5288 OO‘ s Sequence Description OO has got a array A of size n ,defined

捕牛記(1503)解題報告(bfs)

字節數 first 檢測 表示 所有結點 sca c++ fin ++ 解題思路:每到一個坐標點都有三種走法,每個點只走一次,直到第一次發現牛的坐標為止。用廣度優先搜索(Breadth First Search)(bfs) 代碼實現:定義一個標記結點狀態的數組、一個記錄

[LintCode] 618 Search Graph Nodes 解題報告

and value integer search values tee esc mapping ppi DescriptionGiven a undirected graph, a node and a target, return the nearest node to

[LintCode] 599 Insert into a Cyclic Sorted List 解題報告

blog same ted next rom list ron div ger DescriptionGiven a node from a cyclic linked list which has been sorted, write a function to inse

16. 3Sum Closest

ber for assume one ops cto get num else Problem statement: Given an array S of n integers, find three integers in S such that the sum is

歡樂賽解題報告

輸入 不同 eof ~~ ostream 同步 題目 由於 .cpp ~~一場不歡樂的歡樂賽 時間分配::T1做的時候還可以,大約三十分鐘寫了個深搜(鬼知道我為啥不用廣搜,大概是因為快半個月沒寫了)寫完後去研究第二題,剛開始以為是貪心,很快寫了出來,但是自己推了一會舉出了反

[LeetCode]Distinct Subsequences,解題報告

blog ati i++ without || args ack 個數 etc 題目 Given a string S and a string T, count the number of distinct subsequences of T in S. A sub

hdu 5375 - Gray code(dp) 解題報告

auto 當前 width ive data -i int code original Gray code Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Oth

poj - 1185 炮兵陣地 狀壓DP 解題報告

其他 無法 popu mon 多少 mod tdi 遞推關系 r+ 炮兵陣地 Time Limit: 2000MS Memory Limit: 65536K Total Submissions: 21553 Accepted: 8363

leetCode解題報告5道題(十)

ddl peek path sum ron 表示 bar largest ger 不能 題目一:Valid Number Validate if a given string is numeric. Some examples: "0&quo