1. 程式人生 > >LeetCode 2.1.8 3Sum

LeetCode 2.1.8 3Sum

問題描述:Given an array S of n integers, are there elements a; b; c in S such that a + b + c = 0? Find all unique
triplets in the array which gives the sum of zero.
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)

問題分析:我們對原陣列進行排序,然後開始遍歷排序後的陣列,這裡注意不是遍歷到最後一個停止,而是到倒數第三個就可以了。這裡我們可以先做個剪枝優化,就是當遍歷到正數的時候就break,為啥呢,因為我們的陣列現在是有序的了,如果第一個要fix的數就是正數了,那麼後面的數字就都是正數,就永遠不會出現和為0的情況了。然後我們還要加上重複就跳過的處理,處理方法是從第二個數開始,如果和前面的數字相等,就跳過,因為我們不想把相同的數字fix兩次。對於遍歷到的數,用0減去這個fix的數得到一個target,然後只需要再之後找到兩個數之和等於target即可。我們用兩個指標分別指向fix數字之後開始的陣列首尾兩個數,如果兩個數和正好為target,則將這兩個數和fix的數一起存入結果中。然後就是跳過重複數字的步驟了,兩個指標都需要檢測重複數字。如果兩數之和小於target,則我們將左邊那個指標i右移一位,使得指向的數字增大一些。同理,如果兩數之和大於target,則我們將右邊那個指標j左移一位,使得指向的數字減小一些

程式碼:

class Solution
{
public:
	vector<vector<int>>threeSum(vector<int>& num)
	{
		vector<vector<int>> result;
		sort(num.begin(),num.end());//排序陣列

		if(num.empty() || num.back() < 0 || num.front() > 0)
		{
			return result;
		}

		for(int k = 0;k < num.size();k++)
		{
			if(num[k] > 0)
			{
				break;
			}

			if(k > 0 && num[k] == num[k - 1])//防止重複
			{
				continue;
			}

			int target = 0 - num[k];

			int p1 = k + 1;//important
			int p2 = num.size() - 1;

			while(p1 < p2)
			{
				if(num[p1] + num[p2] == target)
				{
					result.push_back(num[k],num[p1],num[p2]);
					while(p1 < p2 && num[p1] == num[p1])
					{
						p1++;
					}

					while(p1 < p2 && num[p2] == num[p2])
					{
						p2--;
					}
					++p1;
					--p2;
				}
				else if(num[p1] + num[p2] < target)
				{
					p1++;
				}
				else
				{
					p2--;
				}	
			}
		}
		return result;
	}
};