zoukankan      html  css  js  c++  java
  • LeetCode: 3SumClosest

    Title :

    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).
    int threeSumClosest(vector<int> &num, int target){
            sort(num.begin(),num.end());
            int min = INT_MAX;
            int result;
            for (int i = 0 ; i < num.size()-2; i++){
                if (i > 0 && num[i] == num[i-1])
                    continue;
                int left = i+1;
                int right = num.size()-1;
                int goal = target - num[i];
                while (left < right){
                    int diff = abs(target - num[left] - num[right] - num[i]);
                    if (diff < min){
                        min = diff;
                        result = num[left] + num[right] + num[i];
                    }
                    if (num[left] + num[right] < goal){
                        while (left < right && (num[left] == num[left+1]))
                            left++;
                        left++;
                    }else if (num[left] + num[right] > goal){
                        while (left < right && (num[right] == num[right-1]))
                            right--;
                        right--;
                    }else{
                        return target;
                    }
                }
            }
            return result;
        }
  • 相关阅读:
    python,可变参数
    python process,queue
    python 进程池Pool
    python 中的set与list,tuple
    python 元组tuple
    深夜装ubuntu
    python中的协程
    python Queue在两个地方
    (转载)Spring mvc中@RequestMapping 6个基本用法小结
    数据库jdbc连接--【DRP】
  • 原文地址:https://www.cnblogs.com/yxzfscg/p/4419369.html
Copyright © 2011-2022 走看看