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

    思路:

    与之前的求解方法一样,只不过本题变成求和最接近的和,用绝对值即可。

    程序里面的一个技巧就是,遇到重复数字直接跳过,这是因为,第一次的时候,就已经考虑后面的了,比如说1,1,1,2

    第一个选择1的时候,后面就已经有left等于后面的1,所以同样的道理,最后也是要从后往前找不同的第一个点,至于找到了,相同的pass。

    程序的另外一个技巧就是,遇到等于目标数字的,直接赋值,而有不同的,再去进行比较,这里指绝对值。至于后面大于小于的情况,作同样处理。

    代码:

    class Solution {
    public:
        int threeSumClosest(vector<int>& nums, int target) {
            int length=nums.size();
            sort(nums.begin(),nums.end());
            int left=0,right=length-1;
            int res=INT_MAX,result=target;
            for(int i=0;i<length-2;i++){
                if(i>0 && nums[i]==nums[i-1]){
                    continue;
                }
    
                int a=nums[i];
                int left=i+1,right=length-1;
                while(left<right){
                    int b=nums[left],c=nums[right];
                    int sum=a+b+c;
    
                    if(sum==target){
                        return target;
                    }else{
                        if(abs(target-sum)<=res){
                            res=abs(target-sum);
                            result=sum;
                        }
    
                        if(sum>target){
                            right--;
                            while(nums[right]==nums[right+1]){
                                right--;
                            }
    
                        }
    
                        if(sum<target){
                            left++;
                            while(nums[left]==nums[left-1]){
                                left++;
                            }
                        }
                    }
    
                }
            }
            return result;
        }
    };


  • 相关阅读:
    OCP 071中文考试题库(cuug整理)第25题
    OCP 071中文考试题库(cuug整理)第24题
    OCP 071中文考试题库(cuug整理)第23题
    OCP 071中文考试题库(cuug内部资料)第22题
    Oracle OCP 071【中文】考试题库-第21题
    Oracle OCP 071【中文】考试题库-第20题
    Oracle OCP 071【中文】考试题库-第18题
    Oracle OCP 071中文考试题库-第11题
    接口与实现
    solr学习0
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519873.html
Copyright © 2011-2022 走看看