16. 3Sum Closest

本文介绍了一种寻找数组中三个整数之和最接近给定目标值的有效算法。通过先对数组进行排序,然后使用双指针技巧来减少搜索次数,实现O(n^2)的时间复杂度。

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).

思路:这种除了遍历还有什么好办法噢?嘤嘤嘤…它要我找最接近的,本来数字是任意给你的。O(n^3)
非常重要的一点,我们要先把它变成有序的!!!

这里用了冒泡排序,时间O(n^2).
一开始冒泡排序都写错了,把j的初值条件写成了i+1.当成遍历时候的情况了。冒泡它一次冒个最值出来,这里是最大值,所以判断条件范围可以越缩越小,但都要从0开始遍历。

        for( i=0;i<length-1;i++){
            for(j=0;j<length-i-1;j++){
                if(nums[j]>nums[j+1]){
                    temp=nums[j];
                    nums[j]=nums[j+1];
                    nums[j+1]=temp;
                }
            }
       }

排完序后,用左右两指针,更新距离和三个数字之和。

class Solution {
    public int threeSumClosest(int[] nums, int target) {
       //先用冒泡排序法,无序变有序。
       bubble_sorted(nums);
         for(int i=0;i<nums.length;i++) System.out.println(nums[i]);
       int length=nums.length;
       int left,right;
       int dis=Integer.MAX_VALUE;
       int sum=0;
       for(int i=0;i<length-2;i++){
           left=i+1;
           right=length-1;
           while(left<right){
               if(Math.abs(nums[left]+nums[right]+nums[i]-target)<dis){
                   sum=nums[left]+nums[right]+nums[i];
                   dis=Math.abs(nums[left]+nums[right]+nums[i]-target);
               }
               if(nums[left]+nums[right]+nums[i]==target){
                   sum=nums[left]+nums[right]+nums[i];
                   break;
               }
               else if(nums[left]+nums[right]+nums[i]>target){
                    right--;
               }
               else{
                     left++;
               }
           }
       }
       return (sum);
    }

   private static void bubble_sorted(int[] nums){
       int i,j;
       int length=nums.length;
       int temp;
       for( i=0;i<length-1;i++){
            for(j=0;j<length-i-1;j++){
                if(nums[j]>nums[j+1]){
                    temp=nums[j];
                    nums[j]=nums[j+1];
                    nums[j+1]=temp;
                }
            }
       }
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值