Lexi's Leetcode solutions

[leetcode] 3Sum | 三个数加和等于0,要求无重复,不能用set

Posted on: October 18, 2013

本来以为是弱智题,但是要求不能duplicate之后,发现代码还真不好写了。难怪通过率只有16%这么低。

  • 如何处理“和上一个一样就不要做了”这种duplicate情况?(形成自己的代码习惯)
    • if (i > 0 或类似condition && num[i] == num[i – 1]) continue;
    • 这样可以保证永远笼罩在while (some condition)的保证之下,用continue就不会出现越界等情况。
    • 如果是递归,外层没有while,则用while (boundary &&  num[i] == num[i – 1[) {i++;}
public ArrayList<ArrayList> threeSum(int[] num) {
    ArrayList<ArrayList> result = new ArrayList<ArrayList>();
    Arrays.sort(num);
    for (int i = 0; i < num.length; i++) { 			
        if (i > 0 && num[i] == num[i - 1])
            continue;
	int x = 0 - num[i];
	int p = i + 1, q = num.length - 1;
	while (p < q) {
            if (p > i + 1 && num[p] == num[p - 1]) {
                p++;
                continue;
            }
            if (q < num.length - 1 && num[q] == num[q + 1]) {
                q--;
                continue;
            }
	    if (num[p] + num[q] == x) {
                ArrayList triple = new ArrayList();
		triple.add(num[i]);
		triple.add(num[p]);
		triple.add(num[q]);
		result.add(triple);
	    } else if (num[p] + num[q] < x) {
		p++;
	    } else {
	        q--;
	    }
	}
    }
    return result;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: