LeetCode_三数之和

在这里插入图片描述

算法思路:排序+双指针

  1. 先判断数组的大小是否大于2,若小于3,则返回空数组
  2. 若数组大小大于2,进行排序
  3. 以负数作为判断数进行循环,两指针一头一尾,若头尾两指针的value和等于选定的判断数的负数,则把这三个数加入到vector
  4. 若value和小于判断数的负数,说明和太小,低指针++;若value和大于判断数的负数,说明和太大,高指针–
vector<vector<int>> result;        
int Length = int(nums.size());        
if(Length<=2)        
{            
	return result;        
}        
int possibleSize = Length - 2;
sort(nums.begin(),nums.end());        
for(int i=0;i<possibleSize;i++)        
{            
	int intNow = nums[i];            
	if(intNow > 0)            
	{                
		break;            
	}            
	int negativeNow = 0 - intNow;            
	int _low = i + 1;            
	int _high = Length - 1;            
	while(_low < _high)            
	{                
		int NowLow = nums[_low];                
		int NowHigh = nums[_high];                
		if(NowLow+NowHigh== negativeNow)                
		{
			result.push_back({intNow,NowLow,NowHigh});                    	 
			while(_low<_high&&nums[_low] == NowLow)                    
			{                        
			_low++;                    
			}                    
			while(_low<_high&&nums[_high] == NowHigh)                    
			{                        
			_high--;                    
			}                                  
		}               
		else if (NowLow + NowHigh <negativeNow)                
		{                   
			_low++;                
		}                
		else if (NowLow + NowHigh >negativeNow)                
		{                   
			_high--;                
		}
            }            
            while(i + 1<possibleSize&&nums[i] == nums[i + 1])            
            {                
            	i++;            
            }

}        
return result;

在这里插入图片描述

发布了38 篇原创文章 · 获赞 1 · 访问量 798

猜你喜欢

转载自blog.csdn.net/weixin_45774706/article/details/104664149