力扣第15题三数之和和第16题最接近的三数之和

题目:

思路:

1.先将输入的数组进行排序
2.对第一个数据进行判断,第一个必须位负数,大于零才可能三位数的之和为零 
3.使用双指针,从第一个数据的后一位开始向后循环进位,后面的指针从最后一位开始进位
4.要进行去重,因为要考虑例如[-1,-1,0,2,2]因为数组中有相同数据,所以在循环的时候会多次运算一遍,但是得出结果只能是一组相同的,所以进行判断,相同则直接跳过这一位;

class Solution {

    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> res = new ArrayList<List<Integer>>();

        Arrays.sort(nums);

        for(int i = 0; i < nums.length - 2; i++){

            if(nums[i] > 0){

                break;

            }

            if(i > 0 && nums[i] == nums[i - 1]){

                continue;

            }

            int start = i + 1;

            int end = nums.length - 1;

            while(start < end){

                if(nums[i] + nums[start] + nums[end] == 0){

                    List<Integer> list = new ArrayList<Integer>();

                    list.add(nums[i]);

                    list.add(nums[start]);

                    list.add(nums[end]);

                    res.add(list);

                    while (start<end && nums[start+1] == nums[start]){

                    start++;

                }

                start++;

                while (start<end && nums[end-1] == nums[end]){

                    end--;

                }

                end--;

                }

                else if(nums[i] + nums[start] + nums[end] > 0){

                    end--;

                }

                else{

                    start++;

                }

            }

        }

        return res;

    }

}

题目:

 思路:

1.先假设数组的前三位值之和为最接近或者等于输入值。
2.其次使用双指针,从第一位数与双指针指向的值相加,将前面定义的三位数之和与 后面循环所得到的三位数之和与输入值做差
3.使用绝对值进行比较,那个绝对值小赋值为最为接近,等循环完后输出最为接近值

class Solution {

    public int threeSumClosest(int[] nums, int target) {

        Arrays.sort(nums);

        int approach = nums[0] + nums[1] + nums[2];

        int left,right;

        for (int i = 0; i < nums.length; i++) {

            left = i + 1;

            right = nums.length- 1;

            while (left < right) {

                int sum = nums[i] + nums[left] + nums[right]; 

                if (Math.abs(sum - target) < Math.abs(approach - target)){

                    approach = sum;

                } 

                if (approach == target) {

                    return target;

                } else if (sum > target) {

                    right --;

                } else if (sum < target) {

                    left ++;

                }

            }

        }

        return approach;

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值