博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode(15)题解--3Sum
阅读量:4501 次
发布时间:2019-06-08

本文共 2099 字,大约阅读时间需要 6 分钟。

https://leetcode.com/problems/3sum/

题目:

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

 

For example, given array S = {-1 0 1 2 -1 -4},    A solution set is:    (-1, 0, 1)    (-1, -1, 2)

 

方法一:

两层循环+二分查找,复杂度O(n^2 logn). 太慢了

1 class Solution { 2 public: 3     vector
> threeSum(vector
& nums) { 4 set
> res; 5 vector
> output; 6 vector
sol; 7 sort(nums.begin(),nums.end()); //sort first 8 int i,j,k,t,x,n=nums.size(); 9 for(i=0;i
> :: iterator iter;23 for(iter=res.begin();iter!=res.end();iter++){24 output.push_back(*iter);25 }26 return output;27 }28 int findSol(int target,vector
nums,int begin,int end){29 if(nums[begin]==target)30 return begin;31 if(nums[end]==target)32 return end; 33 if(nums[begin]>target||nums[end]
target){41 end=mid-1;42 }43 else44 begin=mid+1;45 }46 return -1;47 }48 };

 

 

方法二:  一层循环加two sum思想(https://leetcode.com/problems/two-sum/),O(n^2).

1 class Solution { 2 public: 3     vector
> threeSum(vector
& nums) { 4 sort(nums.begin(),nums.end()); 5 vector
> res; 6 int i,t,a,b,k,n=nums.size(); 7 for(i=0;i
t){17 b--;18 }19 else{20 vector
sol(3,0);21 sol[0]=nums[i];22 sol[1]=nums[a];23 sol[2]=nums[b];24 res.push_back(sol);25 while (a < b && nums[a] == sol[1]) 26 a++;27 while (a < b && nums[b] == sol[2]) 28 b--;29 }30 }31 while (i + 1 < nums.size() && nums[i + 1] == nums[i]) 32 i++;33 }34 35 //deduplicate, but it is so slow!36 //sort(res.begin(), res.end()); 37 //res.erase(unique(res.begin(), res.end()), res.end());38 return res;39 }40 };

 

转载于:https://www.cnblogs.com/aezero/p/4823306.html

你可能感兴趣的文章
sql语句 字段的赋值
查看>>
解决IOS safari下滑动的“橡皮筋”效果
查看>>
asp.net 得到一个文件夹下的所有文件夹及子文件夹名,得到所有文件名,文件大小,文件夹大小...
查看>>
从keystore(jks)文件中提取私钥
查看>>
调整数组顺序使奇数位于偶数前面
查看>>
css3的3D和2D
查看>>
简单的响应式布局的实现
查看>>
jQuery(属性操作)
查看>>
Python之路【第九篇】:Python面向对象
查看>>
background和background-image一点小区别
查看>>
ASCII码对照表
查看>>
HackerRank "Training the army" - Max Flow
查看>>
jquery next()方法
查看>>
深入剖析js命名空间函数namespace
查看>>
SQLHelper
查看>>
用标准Struts2+mvc写的用户管理
查看>>
Cocos2d-x 3.0 编译出错 解决 error: expected &#39;;&#39; at end of member declaration
查看>>
Ubuntu12.04下载Repo
查看>>
python基础教程_学习笔记10:异常
查看>>
MATLAB——scatter的简单应用
查看>>