15. 3Sum
来源:互联网 发布:tdi最新价格数据 编辑:程序博客网 时间:2024/05/18 00:07
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:
- 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)
【思路】先整体排序,固定第一个数,第二个数从左往右,第三个数从右往左,判断他们三个的和。
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; vector<int> temp; int len = nums.size(); if(len<3) return result; sort(nums.begin(), nums.end()); for(int i = 0; i < len; i++) { while((i>0)&& i < len && (nums[i]==nums[i-1])) i++; int j = i+1; int k = len-1; while(j < k) { int sum = nums[i]+nums[j]+nums[k]; if(sum==0) { temp.push_back(nums[i]); temp.push_back(nums[j]); temp.push_back(nums[k]); result.push_back(temp); temp.clear(); j++; k--; while(j < k && nums[j]==nums[j-1]) j++; while(j < k&& nums[k]==nums[k+1]) k--; } else if(sum < 0) { j ++; //skip same j while(j < k && nums[j] == nums[j-1]) j ++; } else { k --; //skip same k while(k > j && nums[k] == nums[k+1]) k --; } } } return result; }};
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
- 如何用形象的比喻描述大数据的技术生态?Hadoop、Hive、Spark 之间是什么关系?
- java 505异常,原因http协议参数间不能为空
- 设计模式(六)原型模式
- C/C++时间函数使用方法
- java程序用命令行编译
- 15. 3Sum
- ROS Jade配置Gazebo5:jade官方教程+gazebo官方教程的汇总——Ubuntu系统14.04
- android的消息处理机制(图+源码分析)——Looper,Handler,Message
- android 跳转到指定应用程序
- 高速PCB设计绕等长一定要绕个山路十八弯太算吊?
- I00003 贝尔三角形
- mybatis的resultMap使用
- 官网Unity3Dshader解析,好文章,记录下
- ubuntu下tftp服务器简单搭建