zoukankan      html  css  js  c++  java
  • 3 3Sum closest_Leetcode

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

    To enumerate a subset of specified length without repetition, the best method is to keep the index increasing. (e.g. 0,1,2; 1,3,4)

    The brute force enumeration use a 3-for loop which is O(n^3).

    Remind the technique we used in 2Sum, we could sort first then start from the begin and the end to get the most closest sum.

    So here we put the first num in a for loop, and use the technique in 2Sum to enumerate the other two num. The time complexity is O(n^2). Note the index of the elements in the subset is increasing. 

    FIRST ERROR: Since we want to find the closest, I firstly wrongly used right-- to change the while loop index. How stupid error it is... I should change the index according to the sum compared with the target.

    Code:

    lass Solution {
    public:
        int threeSumClosest(vector<int> &num, int target) {
            int n = num.size();
            if(n < 3) return 0;
            int closest = INT_MAX;
            int mingap = INT_MAX;
    
            sort(num.begin(), num.end());
            for(int i = 0; i < n-2; i++)
            {
                int left = i+1, right = n-1;
                while(left < right)
                {
                    int cursum = num[i] + num[left] + num[right];
                    int gap = abs(target - cursum);
                    if(gap < mingap)
                    {
                        closest = cursum;
                        mingap = gap;
                    }
                    if(cursum < target) left++;   // first error
                    else if(cursum > target) right--;
                    else return target;
                }
            }
            return closest;
        }
    };
    

      

  • 相关阅读:
    助教观察记录5(10/21-11/3)
    助教观察记录4(10/07-10/20)
    助教观察记录3(9/23-10/06)
    助教观察记录1(9/5-9/15)
    2019年春季学期《C语言程序设计II》课程总结
    2020软件工程个人作业06——软件工程实践总结作业
    软件工程第二次作业
    2020软件工程作业3
    2020软件工程作业01
    神必高考数学题乱写
  • 原文地址:https://www.cnblogs.com/avril/p/4020698.html
Copyright © 2011-2022 走看看