在给出零和的数组中查找所有唯一的三元组



我很难回答这个问题。因此,我试图以字符串的形式显示正确的解决方案,但在最后一个for循环中遇到了困难。还有没有一种方法可以对这些数组进行排序,或者只添加arrays.sort函数?

问题如下:

//Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all //unique triplets in the array which gives the sum of zero.
//Note:
//The solution set must not contain duplicate triplets.
//Example:
//Given array nums = [-1, 0, 1, 2, -1, -4],
//A solution set is:
//[
//  [-1, 0, 1],
//  [-1, -1, 2]
//]

这就是我目前拥有的


class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//Arrays.sort(nums);
int isZero = 0;

for(int i = 0; i < nums.length; i++)
{
for(int j = i+1; j< nums.length; j++)
{
for(int x = i + 2; x < nums.length;x++ )
{
if(nums[i] + nums[j]+ nums[x] == isZero)
{


}
}
}
}
return Collections.emptyList();

}
}

您需要一个外部List来存储数组,并且在每次匹配时保存3个值

public List<List<Integer>> threeSum(int[] nums) {
int isZero = 0;
List<List<Integer>> result = new ArrayList<>();
for(int i = 0; i < nums.length; i++){
for(int j = i+1; j< nums.length; j++){
for(int x = i + 2; x < nums.length;x++ ){
if(nums[i] + nums[j]+ nums[x] == isZero){
result.add(Arrays.asList(nums[i], nums[j], nums[x]));
}
}
}
}
return result;        
}

如果你的意思是对三元组进行排序,那么没有重复,

  • 使用Set
  • 在之前对内部列表进行排序
  • 在两个第一个循环的结束边界上,可以使用-2-1删除无用的迭代
public static Set<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> result = new HashSet<>();
int isZero = 0;
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
for (int x = i + 2; x < nums.length; x++) {
if (nums[i] + nums[j] + nums[x] == isZero) {
List<Integer> tmp = Arrays.asList(nums[i], nums[j], nums[x]);
tmp.sort(Comparator.naturalOrder());
result.add(tmp);
}
}
}
}
return result;
}

下面的代码通过了所有测试。唯一的问题是O(n*2(的时间复杂性,其中对于非常大的输入,时间超过。欢迎,如果有人改进了算法。

class Solution {
public List<List<Integer>> threeSum(int[] A) {

if ( A.length <= 2 ) return List.of();

Set<List<Integer>> set = new HashSet<>();

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

for (int j = i + 1; j < A.length ; ++j) {
int thirdNumber = - ( A[i] + A[j] ) ;
List<Integer> tempp = Arrays.stream(A).boxed().collect(Collectors.toList());
tempp.remove(Integer.valueOf(A[i]));
tempp.remove(Integer.valueOf(A[j]));
if (tempp.contains(Integer.valueOf(thirdNumber))) {
List<Integer> temp = Arrays.asList(A[i], A[j], thirdNumber);
Collections.sort(temp);
set.add(temp);
}               
}
}

return new ArrayList<>(set);
}

}

您可以在收集这些三元组之前对数组进行排序,然后对这些三元组也进行排序。

public Set<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);  // Sort the array
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
for (int x = j + 1; x < nums.length; x++) {
if (nums[i] + nums[j] + nums[x] == 0) {
res.add(Arrays.asList(nums[i], nums[j], nums[x]));
}
}
}
}
return res;
}

最新更新