Leetcodes Solutions 15 3Sum

Leetcodes Solutions 15 3Sum

來自專欄 Leetcodes Solutions

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

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]]

思路1

先排序,遍曆數字的每個元素。

以每個元素的負數作為求和的目標,找出那個元素後面的合適的兩個數。

class Solution{public: vector<vector<int>> threeSum(vector<int>& num){ vector<vector<int>> res; std::sort(num.begin(), num.end()); for(int i = 0; i < num.size(); i++){ int target = -num[i]; int front = i + 1; int back = num.size() - 1; while(front < back){ int sum = num[front] + num[back]; if(sum < target) front++; else if(sum > target) back--; else{ vector<int> triplet(3, 0); triplet[0] = num[i]; triplet[1] = num[front]; triplet[2] = num[back]; res.push_back(triplet); while(front < back && num[front] == triplet[1]) front++; while(front < back && num[back] == triplet[2]) back--; } } while(i + 1 < num.size() && num[i + 1] == num[i]) i++; } return res; }};

推薦閱讀:

GacUI終於獲得第一個願意跟我溝通的商業的case了
關於在坐標系中旋轉平移物體的理論基礎解析
楚河漢界
偽·從零開始學Python - 2.1 面向過程的程序設計簡述

TAG:編程 | 演算法 | 數據結構 |