【leetcod】3Sum —C++
来源:互联网 发布:mac英文输入法联想 编辑:程序博客网 时间:2024/06/05 09:48
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)问题:给一个数组,然后选取三个数相加为零。利用排序来做,使第一个数 i 从0到n-1循环,第二个数 j 从i+1开始,第三个数从 n-1开始,且j < k。
在这中间要判断去重的问题。举个例子,假设这三个数相加为零了,此时考虑 nums[j+1] == nums[j] 则说明重复,则++j;
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; if(nums.size() >= 3) { sort(nums.begin(),nums.end()); int size = nums.size(); int i = 0; while(i < size) { if(nums[i] > 0) break; for(int j = i + 1,k = size - 1;j < k;) { if( (nums[i] + nums[j] + nums[k]) == 0) { vector<int> ivec; ivec.push_back(nums[i]); ivec.push_back(nums[j]); ivec.push_back(nums[k]); result.push_back(ivec); ++j; while(j < size && nums[j - 1] == nums[j]) ++j; //去重 --k; while(k < size && nums[k + 1] == nums[k]) --k; //去重 } else if((nums[i] + nums[j] + nums[k]) < 0) { ++j; while(j < size && nums[j - 1] == nums[j]) ++j;//则没有必要再次循环, } else { --k; while(k < size && nums[k + 1] == nums[k]) --k;<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">//没有必要再次循环,</span> } } ++i; while(i < size && nums[i - 1] == nums[i]) ++i;<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">//则没有必要再次循环,</span> } return result; } return result; }};
0 0
- 【leetcod】3Sum —C++
- [leetcod][two pointers] 4Sum
- leetcod
- Binary Tree Maximum Path Sum Leetcod c++
- LeetCod 339.Nested List Weight Sum
- LeetCod之Search in Rotated Sorted Array (C++)
- [C++]LeetCode: 70 3Sum
- C实现 LeetCode->3Sum
- leetcode 3sum c语言
- Leetcode c语言-3Sum
- LeetCode刷题(C++)——3Sum(Medium)
- 15. 3Sum/16. 3Sum Closest(C++)
- [leetcod] Balanced Binary Tree
- leetcod Wildcard Matching
- Reorder List leetcod
- Partition List -- leetcod
- leetcod--Reverse Bits
- leetcod--Missing Number
- 谈游戏服务端开发(2 )
- 编程时的零散笔记
- LDA主题模型简介
- Android 开发资源连接地址
- socket编程 及select poll epoll示例
- 【leetcod】3Sum —C++
- 02-mongodb图形化工具MongoVUE
- ubuntu 安装配置shadowsocks-qt5
- C++自定义 operator new
- sublime text3一些技巧
- Linux网络编程echo简单示例2--select实现
- 构造函数
- 面临毕业,很迷茫
- Oracle(八)PL/SQL 流程控制(多图高清~)