3 sums题解
来源:互联网 发布:网络造字 编辑:程序博客网 时间:2024/05/21 19:03
题干:
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)
Difficulty: Medium
翻译:
给一个数列和一个目标target,找三个数,相加之和是target,并且三个数不能是重复点,要递增顺序
分析:
sum系列题的第二道,跟2sum和4sums是承上启下的作用,实际上这题有两种解法,一种是转化成上一道题,不过外面套一个for循环,然后把问题转化为2sum,另一种解法是用三个指针,一个指针指向当前元素,定位num1,另外两个指针在num1-(n-1)的位置两头开始,往中间走,找num2和num3,两种方法的唯一区别就在于是否利用辅助空间,时间复杂度都是一样的O(n²)
sum系列一共有4道题,我们这两道用map,下两道用指针:
class Solution {public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> ret; if (nums.size() <= 2) return ret; map<int, int> Hash_map; sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size(); i++) Hash_map[nums[i]] = i; //加一层for循环 for (int i = 0; i < nums.size(); i++) { int target = 0 - nums[i]; vector<int> curr; //内部完全是2sum问题 for (int j = i + 1; j < nums.size(); j++) { int rest_val = target - nums[j]; if (Hash_map.find(rest_val) != Hash_map.end()) { int index = nums[rest_val]; if (index == j || index == i) continue; if (index > j) { curr.push_back(nums[i]); curr.push_back(nums[j]); curr.push_back(nums[index]); ret.push_back(curr); } } while (j < nums.size() - 1 && nums[j] == nums[j + 1]) j++; } while (i < nums.size() - 1 && nums[i] == nums[i + 1]) i++; } for (int i = 0; i < ret.size(); i++) { if(equal(ret[i],ret[i+1])) } return ret; }};
时间复杂度为O(n²),空间复杂度为O(n)
0 0
- 3 sums题解
- 2Sums&3Sums
- 3 sums
- 3Sums
- codechef Sums in a Triangle题解
- USACO section2.2 Subset Sums题解&代码
- UVa-11997 K Smallest Sums 题解
- 题解Find K Pairs with Smallest Sums
- 【leetcode】3sums
- [leetcode]-3sums @python
- Sums
- sums
- 【Hackerrank University2】【JZOJ5008】Querying Sums on Strings 题解
- 具体数学笔记(3)-Sums(2)
- LeetCode之16----3Sums Closest
- Sums of Sums
- POJ 3092 Non-divisible 2-3 Power Sums 笔记
- Alternating Sums
- hdoj4810Wall Painting【组合数学+位运算】
- 优先深度搜索和广度搜索
- MCS_ACM DFS解题报告
- (一)spark学习笔记-开发环境
- 医院业务系统设计(三) --- 患者管理之预约系统
- 3 sums题解
- 连载《一个程序猿的生命周期》- 43.我被这个时代淘汰了吗? ---2016年开篇,春节祝福!!!
- iOS开发实践之网络检测Reachability
- 互联网行业职位介绍——PM,RD,FE,UE,UI,QA,OP,DBA,BRD,MRD, PRD,FSD等
- jQuery入门及各种选择器讲解
- JavaScript > module模式
- 连载《一个程序猿的生命周期》- 44.感谢,我从事了IT相关的工作 --- 《生存》篇结束,全集下载
- Automation UI testing with VNC
- HTML/CSS——插入样式表的三种方法