1. 程式人生 > >[Leetcode] 3Sum

[Leetcode] 3Sum

ems set down source push_back cpp 麻煩 數組元素 gin

3Sum 題解

原創文章,拒絕轉載

題目來源:https://leetcode.com/problems/3sum/description/


Description

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.

Example


For example, given array S = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Solution


class Solution {
private:
    vector<vector<int> > twoSum(vector<int>& nums, int end, int target) {
        vector<vector<int> > res;
        int low = 0
; int high = end; while (low < high) { if (nums[low] + nums[high] == target) { vector<int> sum(2); sum[0] = nums[low++]; sum[1] = nums[high--]; res.push_back(sum); // 去重 while
(low < high && nums[low] == nums[low - 1]) low++; while (low < high && nums[high] == nums[high + 1]) high--; } else if (nums[low] + nums[high] > target) { high--; } else { low++; } } return res; } public: vector<vector<int> > threeSum(vector<int>& nums) { vector<vector<int>> res; int size = nums.size(); if (size < 3) return res; sort(nums.begin(), nums.end()); for (int i = size - 1; i >= 2; i--) { if (i < size - 1 && nums[i] == nums[i + 1]) // 去重 continue; auto sum2 = twoSum(nums, i - 1, 0 - nums[i]); if (!sum2.empty()) { for (auto& sum : sum2) { sum.push_back(nums[i]); res.push_back(sum); } } } return res; } };

解題描述

這道題是Two Sum的進階,解法上采用的是先求Two Sum再根據求到的sum再求三個數和為0的第三個數,不過題意要求不一樣,Two Sum要求返回數組下標,這道題要求返回具體的數組元素。而如果使用與Two Sum相同的哈希法去做會比較麻煩。

這裏求符合要求的2數之和用的方法是,先將數組排序之後再進行夾逼的辦法。並且為了去重,需要在2sum和3sum都進行去重。

[Leetcode] 3Sum