Leetcode初学——最接近的三数之和

题目:

这道题的意思和之前的三数之和的题目非常相似,如果没做过三数之和的同学可以先从三数之和入手,再回来看这道题,思路会非常清晰

和三数之和一样三指针遍历,但是要注意的是,我们找的是最接近的答案,也就是二者之差的绝对值要最小

上代码:

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        int res=Integer.MAX_VALUE/2;
        Arrays.sort(nums);
        int n=nums.length;
        int i=0,j=i+1,k=n-1;
        for(i=0;i<n-2;i++){
            j=i+1;
            k=n-1;
            while(j<k){
                int s=nums[i]+nums[j]+nums[k];
                if(Math.abs(s-target)<Math.abs((res-target))) res=s;
                if(s<target) j++;
                else if (s>target) k--;
                else return res;
            }
        }
        return res;
    }
}

代码部分应该没有什么很难懂的地方,如果有不明白的可以在评论留言,我都会及时回复的

想看下三数之和解法的可以看我的前一篇博文

博文地址:https://blog.csdn.net/qq_39377543/article/details/104056406

发布了25 篇原创文章 · 获赞 3 · 访问量 438

猜你喜欢

转载自blog.csdn.net/qq_39377543/article/details/104060262
今日推荐