zoukankan      html  css  js  c++  java
  • LeetCode 016 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).

    分析:

    和3Sum很像,设一个gap,每次都比较更新gap!

    ① gap == 0,则返回,因为题目说明只有一个解;

    ② gap > 0,q--;

    ③ gap < 0,p++;

    ④ 直到p == q。

    代码如下:

    class Solution {
    public:
        int threeSumClosest(vector<int> &num, int target) {
            
            int result = 0;
            int min_gap = INT_MAX;
            
            sort(num.begin(), num.end());
            
            for(int i = 0; i < num.size(); i++){
                
                int p = i + 1, q = num.size() - 1;
                
                while(p < q){
                    int sum = num[i] + num[p] + num[q];
                    int gap = abs(sum - target);
                    
                    if(gap < min_gap){
                        result = sum;
                        min_gap = gap;
                    }
                    
                    if(sum < target) 
                        p++;
                    else 
                        q--;
                }
            }
            
            return result;
            
        }
    };

     Java:

        public int threeSumClosest(int[] nums, int target) {
    
            int result = 0;
            int min_gap = Integer.MAX_VALUE;
    
            Arrays.sort(nums);
    
            for (int i = 0; i < nums.length; i++) {
    
                int p = i + 1, q = nums.length - 1;
    
                while (p < q) {
                    int sum = nums[i] + nums[p] + nums[q];
                    int gap = Math.abs(sum - target);
    
                    if (gap < min_gap) {
                        min_gap = gap;
                        result = sum;
                    }
    
                    if (sum < target) {
                        p++;
                    } else {
                        q--;
                    }
                }
            }
    
            return result;
        }
  • 相关阅读:
    053364
    053363
    oracle导出批量表N行记录
    053362
    053361
    053360
    053359
    053358
    053357
    053356
  • 原文地址:https://www.cnblogs.com/510602159-Yano/p/4278876.html
Copyright © 2011-2022 走看看