gpt4 book ai didi

java - 4sum 在 Java 中的实现,来自 leetcode

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:39:34 24 4
gpt4 key购买 nike

leetcode 中的问题陈述说:

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

注意:

Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.

关于这个四和问题,我有两个问题:

  1. 我哪里错了?编译后的代码无法通过所有测试,但我认为代码应该是正确的,因为它只是使用暴力来解决问题。
  2. 是否有任何有效的方法来解决四和问题而不是这个 O(n^4) 运行时算法?

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class FourSumSolution{
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target){
ArrayList<ArrayList<Integer>> aList = new ArrayList<ArrayList<Integer>>();
int N = num.length;

for(int i=0; i<N; i++)
for(int j=i+1; j<N; j++)
for(int k=j+1; k<N; k++)
for(int l=k+1; l<N; l++){
int sum = num[i] + num[j] + num[k] + num[l];
if(sum == target){
ArrayList<Integer> tempArray = new ArrayList<Integer>();
Collections.addAll(tempArray, num[i], num[j], num[k], num[l]);
aList.add(tempArray);
}
}
return aList;
}
}

最佳答案

这是一个 O(n^3) 的解决方案

import java.util.Arrays;
import java.util.ArrayList;
import java.util.HashSet;
public class Solution {
public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function

Arrays.sort(num);
HashSet<ArrayList<Integer>> hSet = new HashSet<ArrayList<Integer>>();
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < num.length; i++) {
for (int j = i + 1; j < num.length; j++) {
for (int k = j + 1, l = num.length - 1; k < l;) {
int sum = num[i] + num[j] + num[k] + num[l];
if (sum > target) {
l--;
}
else if (sum < target) {
k++;
}
else if (sum == target) {
ArrayList<Integer> found = new ArrayList<Integer>();
found.add(num[i]);
found.add(num[j]);
found.add(num[k]);
found.add(num[l]);
if (!hSet.contains(found)) {
hSet.add(found);
result.add(found);
}

k++;
l--;

}
}
}
}
return result;
}

关于java - 4sum 在 Java 中的实现,来自 leetcode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11216582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com