3Sum
来源:互联网 发布:火锅烧烤网络营销策划 编辑:程序博客网 时间:2024/06/13 23:18
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]
]
方法: 排序+三个标记,算法复杂度(O2)。
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(),nums.end()); vector<vector<int>> res; if(nums.size() < 3) return res; for(int first = 0; first < nums.size() -2; ++first){ if(first != 0 && nums[first] == nums[first-1]) continue; int second = first + 1, third = nums.size() - 1; while(second < third){ while(second != first + 1 && nums[second] == nums[second - 1]&&second < third) ++second; if(second >= third) break; while(third != nums.size() - 1 && nums[third] == nums[third+1]&&second < third) --third; if(second >= third) break; int temp_sum = nums[first] + nums[second] + nums[third]; if(temp_sum > 0) --third; else if(temp_sum < 0) ++second; else{ res.push_back(vector<int>{nums[first],nums[second],nums[third]}); ++second; --third; } } } return res; }};
0 0
- Two Sum && 3 Sum
- 【Leetcode】3Sum (Sum)
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- leetcode 2 sum 3sum 4sum
- 2Sum 3Sum 4Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 3Sum
- 3SUM
- 3-sum
- 3Sum
- 3Sum
- 3Sum
- 3Sum
- flume 自定义拦截器实现多行读取日志
- linux驱动开发之字符设备框架 -调用过程分析
- spring装配bean的三种方式
- 论文笔记 understanding deep learning requires rethinking generalization
- ajax,json获取action,html获取session中的值,显示登录名
- 3Sum
- C#项目5.4
- vbs脚本demo
- Hibernate分页实现
- java.lang.NoClassDefFoundError: org/apache/log4j/Level的解决方案
- Dogs vs. Cats Redux: Kernels Edition
- 对称矩阵的基本操作及其压缩存储
- Form表单传递List数组属性到后台对象中
- Python实现互联网笔试题-今日头条-3个一组的试题