leetcode15

国庆假期也玩也coding,再不写博客,之前没写注释的代码可能都忘了。。。
以后要开始写写注释。
LeetCode15-3Sum
这道题目出出来就知道暴力搜索肯定是超时的,虽然这样依然抱着侥幸心理试了试,确实超时了,就不贴代码了。

当然考虑Two Sum用map空间来换取时间的方法,我还是尝试了一下。由于是三个数,很有可能要考虑重复的问题,我在代码中使用如下方式来去重:

if(find(result.begin(),result.end(),temp) == result.end())
{
	result.push_back(temp);
}

在两重循环中使用find来判断vector<int>类型的变量temp是否在result结果集中出现,结果是超时的,后来查了一下得知,std::find的时间复杂度是O(n)

参考http://www.cplusplus.com/reference/algorithm/find/  代码:

template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) {
    if (*first==val) return first;
    ++first;
  }
  return last;
}

好了,言归正传,对于3Sum来说,做法是先固定一个数,再对另两个数进行夹逼。

三点注意的是:

1.原数组事先按升序排序。

2.对于固定的第一个数来说,每次循环需要去重。

3.对于夹逼的两个数来说,也需要去重,并且根据三数相加的结果,从两边向中间靠近(要么左数向右要么右数向左,不同时)。

代码:

bool cmp(const int & x,const int & y)
{
	return x<y;
}
class Solution {
public:
    vector< vector<int> > threeSum(vector<int>& nums) {
		int numLen = nums.size();
		int i;
		int j;
		int k;
		vector< vector<int> >result;
		if(numLen  < 3)
		{
			return result;
		}
		vector<int>temp;
		sort(nums.begin(),nums.end(),cmp);
		for(i=0;i<numLen-2;i++)
		{
			j=i+1;
			k=numLen - 1;
			while(j<k)
			{
				if(nums[i] + nums[j] + nums[k] == 0)
				{
					temp.push_back(nums[i]);
					temp.push_back(nums[j]);
					temp.push_back(nums[k]);
					result.push_back(temp);
					temp.clear();
					while(j<k&&nums[j]==nums[j+1])
						j++;
					while(j<k&&nums[k]==nums[k-1])
						k--;
					/*
					if(find(result.begin(),result.end(),temp) == result.end())
					{
						result.push_back(temp);
					}//时间复杂度为O(n)
					*/
				}
				if(nums[i] + nums[j] + nums[k] < 0)
					j++;
				else
					k--;
				//j++;
				//k--;
			}
			while(i<numLen-2&&nums[i]==nums[i+1])
			    i++;
		}

		return result;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值