zoukankan      html  css  js  c++  java
  • LeetCode 3Sum (Two pointers)

    题意

    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.
    找出一个数组中的三个数,使这三个数的和为0。输出所有的组合,不能重复。

    解法

    最简单的思路就是跑一个三层循环,暴力枚举所有组合,很显然会超时。

    然后考虑排序后跑两层循环,第三层改用二分查找,即确定前两个数后用二分来搜第三个数,时间复杂度降到了O(logN * N^2),还是会超时。

    最后,采用了Two Sum这一题的办法,遍历第一个数,然后剩下的两个数用双指针算法来找,这样时间复杂度就降到了O(N^2)

    还有一个问题是判重,这里采用的办法是将三个数拼接起来成为一个数,比如【-1,0,1】就被保存成-101,用Long Long来存,然后放到一个Map里,每次选取新答案时都判断一下这样的组合是不是能在Map里找到。

    class Solution
    {
    public:
    	vector<vector<int>> threeSum(vector<int>& nums)
    	{
    		map<long long,bool>	vis;
    		sort(nums.begin(),nums.end());
    
    		vector<vector<int>>	rt;
    		for(int i = 0;i < nums.size();i ++)
    		{
    			if(nums[i] > 0)
    				break;
    			int	j = i + 1;
    			int	k = nums.size() - 1;
    			while(j < k)
    			{
    				if(nums[i] + nums[j] + nums[k] == 0)
    				{
    					long	long	box = abs(nums[i]);	// 判重
    					int	temp = abs(nums[j]);
    					while(temp)
    					{
    						box *= 10;
    						temp /= 10;
    					}
    					box += abs(nums[j]);
    					temp = abs(nums[k]);
    					while(temp)
    					{
    						box *= 10;
    						temp /= 10;
    					}
    					box += abs(nums[k]);
    					if(nums[i] * nums[j] * nums[k] < 0)
    						box = -box;
    
    					if(vis.find(box) == vis.end())
    					{
    						vis[box] = true;
    						rt.push_back({nums[i],nums[j],nums[k]});
    					}
    					j ++;
    				}
    
    				if(nums[i] + nums[j] + nums[k] < 0)
    					j ++;
    				else	if(nums[i] + nums[j] + nums[k] > 0)
    					k --;
    			}
    		}
    		return	rt;
    	}
    };
    
  • 相关阅读:
    kmeans 初步学习小结
    CAVASS使用经验
    分类之数据集导入matlab方法
    彩色图转化成灰度图
    阈值分割之迭代选择阈值法
    初步学习之FCM
    特征提取学习之HOG原理讲解
    特征提取初步学习之LBP算法
    CodePen.io网站前端设计开发平台
    阿里负责人揭秘面试潜规则
  • 原文地址:https://www.cnblogs.com/xz816111/p/5856839.html
Copyright © 2011-2022 走看看