15. 3Sum
来源:互联网 发布:域名找回 编辑:程序博客网 时间:2024/06/18 08:41
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]]
这道题如果强行遍历的话,时间复杂度是sort()
函数先对数组进行排序,然后再第二轮遍历中采用从中间向两边遍历的方法,找出符合条件的三个数。为了避免重复,可以采用set结构。这道题只有采用巧妙的算法,并且熟悉STL的使用才能做好。
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { set<vector<int>> ans; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) { if (nums[i] > 0) break; int target = 0 - nums[i]; int j = i + 1, k = nums.size() - 1; while (j < k) { if (nums[j] + nums[k] == target) { ans.insert({nums[i], nums[j], nums[k]}); while (j < k && nums[j] == nums[j+1]) j++; while (j < k && nums[k] == nums[k-1]) k--; j++; k--; } else if (nums[j] + nums[k] < target) j++; else k--; } } return vector<vector<int>>(ans.begin(), ans.end()); }};
阅读全文
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
- leet code 605 Can Place Flowers
- js中top、clientTop、scrollTop、offsetTop的区别 文字详细说明版
- command line interface
- 上传头像
- io流小结
- 15. 3Sum
- Java基础知识总结(三)
- 如何从零开始开发一款嵌入式产品(20年的嵌入式经验)(转载)
- SpringBoot学习:SpringBoot整合mybatis
- [线性代数]矩阵的特征值与特征向量
- 最长回文子串——Manacher 算法
- 在VMware中安装Mac OS 操作系统详细教程
- 文件压缩
- VS2017开发activex