zoukankan      html  css  js  c++  java
  • 16. 3Sum Closest(双指针)

    Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    Example:

    Given array nums = [-1, 2, 1, -4], and target = 1.
    
    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

    class Solution {
    public:
        int threeSumClosest(vector<int>& a, int target) {
            const int n = a.size();
            int res = 0;
            if (n < 3) {
                for (auto& ii :a){
                    res+=ii;
                }
                return res;
            }
            std::sort(a.begin(),a.end());
            res = a[0] + a[1] + a[2];
            for(int i = 0; i < n-2; ++i) {
                int low = i + 1;
                int high = n - 1;
                while(low < high) {
                    int cur_sum = a[i] + a[low] + a[high];
                    if (abs(cur_sum - target) < abs(res - target)) {
                        res = cur_sum;    
                    };
                    if (cur_sum > target) {
                        high--;
                    } else if (cur_sum < target) {
                        low++;
                    } else {
                        return target;
                    }
                }
            }
            return res;
            
        }
    };
     1 class Solution {
     2     public int threeSumClosest(int[] nums, int target) {
     3         int res = nums[0]+nums[1]+nums[2];
     4         Arrays.sort(nums);
     5         for(int i = 0 ; i<nums.length-2;i++){
     6             int lo=i+1,hi=nums.length-1;
     7             while(lo<hi){
     8                 int sum=nums[i]+nums[lo]+nums[hi];
     9                 if(sum>target) hi--;
    10                 else lo++;
    11                 if(Math.abs(sum-target)<Math.abs(res-target))
    12                     res = sum;
    13             }
    14         }
    15         return res;
    16     }
    17 }
  • 相关阅读:
    使用 pandas 导出数据
    Vue -- 基础语法和使用
    Django-用户模块与权限系统相关
    rest-framework之权限组件
    rest-framework之认证组件
    rest-framework之解析器
    Markdown -语法说明
    rest-framework之APIView 序列化组件
    eggjs-对接微信公众号
    常用站点
  • 原文地址:https://www.cnblogs.com/zle1992/p/9313719.html
Copyright © 2011-2022 走看看