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

被折叠的 条评论
为什么被折叠?



