Lexi's Leetcode solutions

[leetcode] 4Sum | 四个数加和等于x,不许重复

Posted on: October 18, 2013

和3sum一样,多加一维就多n的复杂度,这个是O(n^3),没看到别人有什么好的做法。注意防止duplicate的地方都标红了,算是比较简洁的two pointers防止dup的方式,以后可以都这么些。

    public ArrayList<ArrayList> fourSum(int[] num, int target) {
    	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;
    		for (int j = i + 1; j < num.length; j++) {     			
                        if (j > i + 1 && num[j] == num[j - 1] ) //一开始写的j > 0,就把1111 x=4的组合给漏掉了
    				continue;
    			int p = j + 1, q = num.length - 1;
    			while (p < q) {
    				int sum = num[i] + num[j] + num[p] + num[q];
    				if (sum == target) {
    					ArrayList quad = new ArrayList();
    					quad.add(num[i]);
    					quad.add(num[j]);
    					quad.add(num[p]);
    					quad.add(num[q]);
					result.add(quad);
					do {p++;} while (p < q && num[p] == num[p - 1]);
					do {q--;} while (p < q && num[q] == num[q + 1]);
    				} else if (sum < target) {
    					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: