首页 > 代码库 > [LeetCode]4 Sum

[LeetCode]4 Sum

类似3Sum,先排序,这后两重for循环,然后对最后的一个数组设两个指针遍历。这里注意重复的问题,例如第一重如果和前面一个数相同则跳过,因为前面的查找肯定包含了本次的情况。

// 4Sum.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <vector>#include <algorithm>#include <map>#include <iostream>using namespace std;class Solution {public:	vector<vector<int> > fourSum(vector<int> &num, int target) {		sort(num.begin(),num.end());		vector<vector<int>>res;		if (num.size() < 4)			return res;		for (int i = 0; i < num.size()-3; i++)		{			if (i>0 && num[i] == num[i - 1])				continue;			for (int j = i + 1; j < num.size() - 2; j++)			{				if (j>i + 1 && num[j] == num[j - 1])					continue;				int p1 = j + 1,p2=num.size()-1;				int sum = target - num[i] - num[j];				while (p1 < p2)				{					if (p1>j + 1 && num[p1] == num[p1 - 1])					{						p1++;						continue;					}					if (p2<num.size()-1&&num[p2] == num[p2 + 1])					{						p2--;						continue;					}					if (p1 >= p2)					{						break;					}					if (num[p1] + num[p2] == sum)					{												vector<int>tempV;						tempV.push_back(num[i]);						tempV.push_back(num[j]);						tempV.push_back(num[p1]);						tempV.push_back(num[p2]);						res.push_back(tempV);						p2--;					}					else if (num[p1]+num[p2]>sum)					{						p2--;					}					else{						p1++;					}				}			}		}		return res;	}};int _tmain(int argc, _TCHAR* argv[]){	Solution ss;	vector<int>test;	test.push_back(1);	test.push_back(0);	test.push_back(-1);	test.push_back(0);	test.push_back(-2);	test.push_back(2);	vector<vector<int> > res = ss.fourSum(test,0);	for (int i = 0; i < res.size(); i++)	{		for (int j = 0; j < res[i].size(); j++)			cout << res[i][j] << ",";		cout << endl;	}	system("pause");	return 0;}

  

[LeetCode]4 Sum