[LeetCode] Two Sum, 3Sum ,3SumCloset , 4Sum

Two Sum:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

struct node
{
	int num,idx;
	node(int n,int i):num(n),idx(i){}
	bool operator<(const node& oth)const
	{
		return n<oth.n;
	}
};

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
	
	vector<node> nums;
    	int n= numbers.size();
	for(int i=0;i<n;i++)
		nums.push_back(node(numbers[i],i+1));
	sort(nums.begin(),nums.end());
	int p1=0,p2=n-1;
	int sum;
	while(p1<p2)
	{
		sum=nums[p1]+nums[p2];
		if ( sum == target )
			break;
		else if ( sum < target )
			p1++;
		else
			p2--;
	}

	vector<int> ans;
	if ( p1< p2 )
	{
		ans.push_back(nums[p1].idx);
		ans.push_back(nums[p2].idx);
	}
	return ans;
			
    }
};


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.

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)
思路是一样的,注意不要有重复答案:

#define vi vector<int> 
#define vvi vector<vi >
class Solution {
public:
    vector<vector<int> > threeSum(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        sort(num.begin(),num.end());
       vvi ans;
       int n=num.size(); 
       for( int i=0;i<n;i++)
       {
           int p1=i+1,p2=n-1;
	       while(p1<p2)
	       {
		       int sum=num[i]+num[p1]+num[p2];
		       if ( sum==0)
		       {
			       vi tmp;
			       tmp.push_back(num[i]);
			       tmp.push_back(num[p1]);
			       tmp.push_back(num[p2]);
			       ans.push_back(tmp);
			       while( p1<p2  && num[p1]==num[p1+1])
				       p1++;
			       p1++;
		       }
		       else if (sum<0)
			       p1++;
		       else
			       p2--;
	       }
	       while(i<n-1&&num[i]==num[i+1])
		       i++;
       }
       return ans;
    }
};


3SumCloset

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution {
public:
    int threeSumClosest(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        sort(num.begin(),num.end());
    int n=num.size();
	assert(n>=3);
	int ans=INT_MAX;
	int dif=INT_MAX;
	for(int i=0;i<n-2;i++)
	{
		int p1=i+1,p2=n-1;
		while(p1<p2)
		{
			int sum=num[i]+num[p1]+num[p2];
			if ( abs(sum-target)<dif )
			{
				dif=abs(sum-target);
				ans=sum;
			}
			if ( sum<target)
				p1++;
			else
				p2--;
		}
	}	
	return ans;
    }
};



4Sum

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

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ? b ? c ? d)
  • The solution set must not contain duplicate quadruplets.

    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)
跟前边一样的思路来避免出现重复答案

#define vi vector<int>
#define vvi vector<vi >
#define pb push_back
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    int n=num.size();
	if ( n<4 )
        return vvi();
	sort(num.begin(),num.end());
	vvi ans;
	vi tmp;
	for(int i=0;i<n;)
	{
		for(int j=i+1;j<n;)
		{
			int p1=j+1,p2=n-1;
			while( p1<p2)
			{
				int sum=num[i]+num[j]+num[p1]+num[p2];
				if ( sum==target)
				{
                    tmp.clear();
					tmp.pb(num[i]);
					tmp.pb(num[j]);
					tmp.pb(num[p1]);
					tmp.pb(num[p2]);
					ans.pb(tmp);
					int t=num[p1];
					while(p1<p2&&num[p1]==t)
						p1++;
				}
				else if (sum<target)
					p1++;
				else
					p2--;
			}
			int t=num[j];
			while(j<n&&num[j]==t)
				j++;
		}
		int t=num[i];
		while(i<n&&num[i]==t)
			i++;
	}
	return ans;
    }	
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值