LeetCode 15. 3Sum
来源:互联网 发布:西安黑马程序员好吗? 编辑:程序博客网 时间:2024/05/22 21:04
3Sum
题目描述:
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]]
题目大意:
给定一个数组,找出三个数,这三个数的和等于0;
首先我们将数列进行排序。我们可以固定地一个数字,然后从用两个指针,一个从前面往后,一个从后面往前。
大体思路就是这样。在具体操作过程中需要考虑重复元素的操作,在固定第一个数的时候,如果当前数字等于之前的数字,那就直接跳过不进行操作。同理,两个指针移动的时候遇到相同元素也要跳过。
题目代码:
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<int> tem(3); vector<vector<int>>ans; int begin, end; sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size(); i++){ if(nums[i] > 0) break; if(i && nums[i] == nums[i-1]) continue; begin = i+1; end = nums.size()-1; while(begin < end){ if(nums[i]+nums[begin]+nums[end] == 0){ ans.push_back({nums[i],nums[begin],nums[end]}); while(begin < end && nums[begin] == nums[begin+1]) begin++; while(begin < end && nums[end] == nums[end-1]) end--; begin++; end--; }else if(nums[i]+nums[begin]+nums[end] > 0){ end--; }else{ begin++; } } } return ans; }};
阅读全文
1 0
- LeetCode 15. 3Sum
- LeetCode --- 15. 3Sum
- [Leetcode] 15. 3Sum
- 【LeetCode】15. 3Sum
- 【leetcode】15. 3sum
- 【leetcode】15. 3Sum
- [leetcode] 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- Leetcode 15. 3Sum
- LeetCode - 15. 3Sum
- [LeetCode]15. 3Sum
- Leetcode 15. 3Sum
- leetcode 15. 3Sum
- leetcode 15. 3Sum
- 【leetcode】15. 3Sum
- Leetcode - 15. 3Sum
- 设计模式
- Python基础——类
- ios开发控制器动画
- Web service是什么?
- java计算两个时间段的精确天数
- LeetCode 15. 3Sum
- Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset
- mysql安装出现error Nr.1045----转
- 阿里云虚拟主机使用教程
- 箭头函数
- Python3 MySQL 数据库连接
- Tomcat7+Redis存储Session
- laravel 加载自定义类文件
- Linux服务器程序后台化,守护进程