15. 3Sum
来源:互联网 发布:4g网络设计思路 编辑:程序博客网 时间:2024/06/02 07:01
题目
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.
Note: 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]]
翻译
查找数组中所有独特的三元组,它们的总和为零。
分析
确定第一个元素后,后面两个元素采用二分左右逼近
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> ret; int n=nums.size(); sort(nums.begin(),nums.end()); for(int i=0;i<n-2;i++){ int left=i+1,right=n-1; if(nums[i]+nums[i+1]+nums[i+2]>0) break; if(nums[i]==nums[i-1]&&i>0) continue; if(nums[i]+nums[n-2]+nums[n-1]<0) continue; while(left<right){ int sum=nums[i]+nums[left]+nums[right]; if(sum>0) right--; else if(sum<0) left++; else { ret.push_back(vector<int>{nums[i],nums[left],nums[right]}); do left++; while(nums[left]==nums[left-1]&&left<right); do right--; while(nums[right]==nums[right+1]&&left<right); } } } return ret; }};do while以前一直理解错误了,正确理解是
do...while 循环是 while 循环的变体。在检查while()条件是否为真之前,该循环首先会执行一次do{}之内的语句,然后在while()内检查条件是否为真,如果条件为真的话,就会重复do...while这个循环,直至while()为假。
0 0
- 15. 3Sum && 16 sum closet && 18 4sum
- 15. 3Sum 和 18. 4Sum
- 1. Two Sum&15. 3Sum
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- 15. 3Sum
- [leetcode] 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- 15. 3Sum
- leetcode 15. 3Sum
- MyEclipse快捷键(个人使用整理)
- jQuery中的事件与动画
- js获取日期以及日期格式化
- PHP怎么打开或者关闭文件?
- 色彩空间
- 15. 3Sum
- poj 2389 BullMath(大数乘法)
- tenserflow实例之最近邻算法
- java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
- centos下使qt调用从windows下导出的sql文件
- c++中构造函数初始化的方法以及主要区别
- <Shader>第一段Shader程序
- 4823: [Cqoi2017]老C的方块
- SOLR搜索引擎