1. 程式人生 > >LeetCode OJ 之 3Sum (三個數的和)

LeetCode OJ 之 3Sum (三個數的和)

題目:

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

給定含有n個整數的數列,求數列中的三個數a,b,c使得a + b + c = 0,找出不重複的數。

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)(非降序排序)
  • The solution set must not contain duplicate triplets.(結果不包含重複的)
    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

思路:

先對陣列排序,然後第一個數先固定,後兩個數一個在最前,一個在最後,進行遍歷。然後第一個數後移,再進行遍歷。

程式碼:

class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) 
    {
        int digit=0;//三個數的和
    	vector<vector<int>> result;
    	int len = num.size();
    	if (len < 3) 
    		return result;
    	sort(num.begin(), num.end());
    	for(int i = 0 ; i < len ; i++)
    	{
    	    //由於題目要求不能有重複的,因此如果當前的數和上次的相同,則忽略
            if(i > 0 && num[i]==num[i-1])  
                    continue;  
    		int j = i + 1;
    		int k = len - 1;
    		while(j < k)
    		{
    		    //同上
    			if(k < len -1 && num[k] == num[k+1])
    			{
    				k--;
    				continue;
    			}
    			//如果當前三個數和較小,則j向後移動,使得總數增大
    			if(num[j] + num[k] + num[i] < digit)
    			{
    				j++;
    			}
    			else
    			{
    				if(num[j] + num[k] + num[i] > digit)
    				{
    					k--;
    				}
    				else
    				{
    					vector<int> cur;//在這裡面定義可以把上次迴圈的cur覆蓋掉
    					cur.push_back(num[i]);
    					cur.push_back(num[j]);
    					cur.push_back(num[k]);
    					result.push_back(cur);
    					j++;
    					k--;
    				}
    
    			}
    		}
    	}
    	return result;
    }
};