• 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;
        }
    };
    
  • 相关阅读:
    0019. Remove Nth Node From End of List (M)
    0018. 4Sum (M)
    0278. First Bad Version (E)
    0273. Integer to English Words (H)
    0017. Letter Combinations of a Phone Number (M)
    0016. 3Sum Closest (M)
    0015. 3Sum (M)
    软件测试常见面试题
    如何快速掌握DDT数据驱动测试?
    selenium--三种等待方式
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6821299.html
Copyright © 2020-2023  润新知