3SUM:避免重复

时间:2016-01-24 17:49:38

标签: java if-statement while-loop

问题: 给定n个整数的数组S,S中是否有元素a,b,c,使得a + b + c = 0?找到数组中所有唯一的三元组,它们总和为零。

为避免重复,我在while循环中使用if子句,我想知道为什么这不起作用。谢谢!

public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    Arrays.sort(nums);

    for (int i = 0; i<nums.length; i++){
        if (i > 0 && nums[i] == nums[i-1]){
            continue;
        }
        int target = -1*nums[i];
        int start = i+1;
        int end = nums.length-1;

        while (start < end){

            if (nums[start] == nums[start+1]){
                start++;
            } 

            if (nums[end] == nums[end--]){
                end--;
            } 

            if (nums[start]+nums[end] == target){
                System.out.printf("found");
                List<Integer> temp = new ArrayList<Integer>();
                temp.add(nums[i]);
                temp.add(nums[start]);
                temp.add(nums[end]);
                result.add(temp);
                start++;
                end--;
            } else if (nums[start]+nums[end] < target) {
                start++;
            } else {
                end--;
            }
        }
    }
    return result;

我在[-1,0,1]上测试,我的代码返回一个空列表。我试图调试并打印一些消息,似乎当i = 1时,在while循环中,它首先进入

if (nums[start] == nums[start+1]){
                start++;
} 

但是当start = 1时,nums [start]不等于nums [start + 1]。这非常古怪。有人可以向我解释一下吗?

2 个答案:

答案 0 :(得分:0)

我决定试一试))

package com.three.sum;

import java.util.*;

public class Main {

    public static void main(String[] args) {
        int[] nums = new int[]{-1, 0, 1};
        List<int[]> res = threeSum(nums);
        System.out.println(res.toString());
    }


    public static List<int[]> threeSum(int[] origNums) {
        List<int[]> result = new ArrayList<int[]>();

        // ++ Use set to avoid duplicates
        Set<Integer> intSet = new HashSet<Integer>();
        for(int k  = 0; k < origNums.length; k++){
            intSet.add(origNums[k]);
        }
        // -- Use set to avoid duplicates

        Integer[] nums = intSet.toArray(new Integer[intSet.size()]);

        for (int i = 0; i < nums.length; i++) {
            int target = - nums[i];
            int start = i + 1;
            int end = nums.length - 1;

            while (start < end) {
                if (nums[start] + nums[end] == target) {
                    int temp[] = new int[3];
                    temp[0] = nums[i];
                    temp[0] = nums[start];
                    temp[0] = nums[end];
                    result.add(temp);
                    start++;
                    end--;
                } else if (nums[start] + nums[end] < target) {
                    start++;
                } else {
                    end--;
                }
            }
        }
        return result;
    }
}

答案 1 :(得分:0)

替换

代码中的字符串
if (nums[end] == nums[end--]) {

 if (nums[end] == nums[end - 1]) {