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;
    	}
    };
    
  • 相关阅读:
    Ajax基础知识详解
    php 基础语法整理
    06 js-递归
    原生js 实现瀑布流布局
    解决高度坍塌问题
    jQuery动画效果
    jQuery增删元素类名
    JQueryTab栏切换(important!)
    jQuery排他思想(important!)
    jQuery设置元素样式
  • 原文地址:https://www.cnblogs.com/xz816111/p/5856839.html
Copyright © 2011-2022 走看看