每日一练_44(2021.7.24) 四数之和(LeetCode)。

这篇博客分享了一段Java代码,用于解决寻找数组中四个元素之和等于给定目标值的问题。代码通过排序和三层循环实现,避免了重复元素的组合,并在找到符合条件的组合后进行优化,提高了效率。博主提供了测试数据并展示了运行结果。

老规矩:大佬代码:https://blog.youkuaiyun.com/jiaobiandianliu/article/details/102471414 值得学习和借鉴。

前几天河南大暴雨,学校又停电,吃饭出门都不方便。电脑又被留在机房拿不出来,哈哈...那几天闷在寝室也是真无聊。

个人微改代码:

import java.util.*;
public class fourNumSum {
    public static void main(String args[]) {
        System.out.println("please enter the size of your array :");
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int a[] = new int[m];
        System.out.println("please enter your data of array :");
        for(int i=0;i<m;i++) {
            a[i]=sc.nextInt();
        }
        System.out.println("please enter your target value :");
        int n = sc.nextInt();
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        res = fourSum(a,n);
        System.out.println("The result :"+res);
        
    }
    
    static List<List<Integer>> fourSum(int nums[],int target){
        List<List<Integer>> List = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        int hah;
        for(int i=0;i<nums.length-3;i++) {
            if(i!=0&&nums[i-1]==nums[i]) continue;
            for(int j=i+1;j<nums.length-2;j++) {
                if(j!=i+1&&nums[j]==nums[j-1]) continue;
                if(nums[j]>0&&nums[i]+nums[j]>target) break;
                for(int k=j+1,l=nums.length-1;k<l;) {
                    hah = nums[i]+nums[j]+nums[k]+nums[l];
                    if(hah>target) {
                        l--;
                    }else if(hah<target) {
                        k++;
                    }else {
                        List.add(Arrays.asList(nums[i],nums[j],nums[k],nums[l]));
                        while(nums[k]==nums[k+1]) {
                            k++;
                            if(k>=l)break;
                        }
                        while(nums[l]==nums[l-1]) {
                            l--;
                            if(k>=l)break;
                        }
                        k++;
                        l--;
                    }
                }
            }
        }
        return List;
    }
}

测试结果:

please enter the size of your array :
6
please enter your data of array :
1
0
-1
0
-2
2
please enter your target value :
0
The result :[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是壮壮没错了丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值