zoukankan      html  css  js  c++  java
  • Leetcode: 16. 3Sum Closest

    Description

    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.

    Example

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

    思路

    • 找出三个数的和同target最相近的和。
    • 同15题类似。记录中间过程出现的最小差值就行

    代码

    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int len = nums.size();
            if(len <= 2) return 0;
            
            int i = 0, j = 0, k = len - 1;
            int res = 0, min_flag = INT_MAX, sum = res, tmp = 0;
            
            sort(nums.begin(), nums.end());
            for(i = 0; i < len; ++i){
                if(i > 0 && nums[i] == nums[i - 1]) continue;
                
                j = i + 1;
                k = len - 1;
                
                while(j < k){
                    if(j > i + 1 && nums[j] == nums[j - 1]){
                        j++;
                        continue;
                    }
                    if(k < len - 1 && nums[k] == nums[k + 1]){
                        k--;
                        continue;
                    }
                   
                    sum = nums[i] + nums[j] + nums[k];
                    tmp = abs(sum - target);
                    if(tmp < min_flag){
                        res = sum;
                        min_flag = tmp;
                    }
                   
                    if(sum > target) k--;
                    else if(sum < target) j++;
                    else return sum;
                }
            }
            
            return res;
        }
    };
    
  • 相关阅读:
    64_q2
    64_q1
    64_p10
    64_p9
    64_p8
    64_p7
    64_p6
    64_p5
    64_p4
    64_p3
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6821299.html
Copyright © 2011-2022 走看看