[LeetCode] 3Sum

简介: This is an extension of the 2Sum problem. The idea is pretty simple (even no need to use hash). Sort the array and then starting from the first elemen...

This is an extension of the 2Sum problem. The idea is pretty simple (even no need to use hash). Sort the array and then starting from the first element, set two pointers left and right: one after the current element and the other at the end of the tail. If all the three elements sum to 0, then they are an answer. Add them to the result. Then you need to be careful to skip the duplicates! If you pay enough attention to the details, this problem has a fairly straightforward implementation without too many tricks.

The final code is as follows.

 1     vector<vector<int>> threeSum(vector<int>& nums) {
 2         vector<vector<int> > res;
 3         if (nums.size() <= 2) return res;
 4         sort(nums.begin(), nums.end());
 5         int l = 0, r = nums.size() - 1;
 6         for (int i = 0; i < (int)nums.size() - 2;) {
 7             int l = i + 1, r = nums.size() - 1;
 8             while (l < r) {
 9                 if (nums[i] + nums[l] + nums[r] == 0) {
10                     vector<int> ans(3);
11                     ans[0] = nums[i];
12                     ans[1] = nums[l];
13                     ans[2] = nums[r];
14                     res.push_back(ans);
15                     while (l < r && nums[l] == ans[0]) l++;
16                     while (r > l && nums[r] == ans[2]) r--;
17                 }
18                 else if (nums[i] + nums[l] + nums[r] > 0) r--;
19                 else l++;
20             }
21             i++;
22             while (i < (int)nums.size() && nums[i - 1] == nums[i]) i++;
23         }
24         return res;
25     }
目录
相关文章
|
存储 算法 安全
LeetCode - #1 Two Sum
我们社区从本期开始会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swift 算法题题解整理为文字版以方便大家学习与阅读。 不积跬步,无以至千里;不积小流,无以成江海,Swift社区 伴你前行。
LeetCode - #1 Two Sum
|
机器学习/深度学习
leetcode - two-sum
leetcode - two-sum
88 0
LeetCode tow Sum 两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
87 0
LeetCode tow Sum 两数之和
|
机器学习/深度学习 Android开发 C++
LeetCode之Two Sum
LeetCode之Two Sum
121 0
|
索引
LeetCode 1:两数之和 Two Sum
题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
911 0
|
算法 索引 C++