zoukankan      html  css  js  c++  java
  • 18. 4Sum

    欢迎fork and star:Nowcoder-Repository-github

    18. 4Sum

    题目

    Given an array S of n integers, are there elements a, b, c, 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: 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]
    ]
    
    

    解析

    class Solution_18 {
    public:
    	vector<vector<int>> fourSum(vector<int>& nums, int target) {
    
    		vector<vector<int>> vecs;
    		
    		if (nums.size()<4)
    		{
    			return vecs;
    		}
    		sort(nums.begin(), nums.end());
    		for (int first = 0; first < nums.size() - 3;first++)
    		{
    			if (first>0&&nums[first]==nums[first-1])
    			{
    				continue;
    			}
    
    			for (int seconde = first + 1; seconde < nums.size() - 2;seconde++)
    			{
    				if (seconde>first+1&&nums[seconde]==nums[seconde-1])
    				{
    					continue;
    				}
    
    				int third = seconde + 1;
    				int fouth = nums.size() - 1;
    
    				while (third<fouth)
    				{
    					vector<int> temp = {nums[first],nums[seconde],nums[third],nums[fouth]};
    					int sum = accumulate(temp.begin(), temp.end(), 0);
    					if (sum==target)
    					{
    						vecs.push_back(temp);
    						third++; fouth--;  //细节问题
    						while (third < fouth&&nums[third] == nums[third - 1])
    						{
    							third++;
    						}
    						while (third < fouth&&nums[fouth] == nums[fouth + 1])
    						{
    							fouth--;
    						}
    	                    // third++; fouth--;放在后面有bug
    
    						//// start++; end--放在后面就是和后面的数比较
    						//while (start < end&&nums[start] == nums[start + 1])
    						//{
    						//	start++;
    						//}
    						//while (start < end&&nums[end] == nums[end - 1])
    						//{
    						//	end--;
    						//}
    						//start++; end--;
    
    						////或者用do() while()循环
    						//do{
    						//	k++;
    						//} while (k < l && ivec[k] == ivec[k - 1]);
    						//do{
    						//	l--;
    						//} while (k < l && ivec[l] == ivec[l + 1]);
    					}
    					else if(sum<target)
    					{
    						third++;
    					}
    					else
    					{
    						fouth--;
    					}
    				}
    			}
    		}
    		return vecs;
    	}
    };
    

    题目来源

  • 相关阅读:
    python读写操作(txt, mat, xls, etc文件)
    开发linux版QQ就是支持未来的国产操作系统
    为知笔记linux绿色版的快速调用
    数学物理中的常见误区
    markdown语法小结
    信息爆炸时代的知识获取
    matlab: 数据的读写
    APS期刊投稿准备: REVTex格式
    markdown基本语法
    常见的数学关系
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8324190.html
Copyright © 2011-2022 走看看