[itint5]三数和为0

http://www.itint5.com/oj/#20

其实是3sum的变种,有重复数字,但是一开始还是写错了。其实是选定一个后,在右边剩余数组里找2sum,找到一组后继续找。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <algorithm>
using namespace std;
typedef tuple<int, int, int> ABC; //存放a,b,c三元组
 
 
//返回所有满足条件的(a,b,c)三元组
vector<ABC> threeSumZero(vector<int> &arr) {
    vector<ABC> ans;
    sort(arr.begin(), arr.end());
    int k = 0;
    while (k < arr.size()) {
        int i = k+1;
        int j = arr.size() - 1;
        while (i < j) {
            if (arr[i] + arr[j] == -arr[k]) {
                ans.push_back(make_tuple(arr[k], arr[i], arr[j]));
                while (i+1 < arr.size() && arr[i] == arr[i+1]) i++;
                while (j-1 >= 0 && arr[j-1] == arr[j]) j++;
                i++;
                j--;
            } else if (arr[i] + arr[j] < -arr[k]) {
                i++;
            } else {
                j--;
            }
        }
        while (k+1 < arr.size() && arr[k] == arr[k+1]) k++;
        k++;
    }
    return ans;
}

  

[itint5]三数和为0

上一篇:Struts学习笔记二--action返回类型及表单值传递


下一篇:[itint5]棋盘漫步