题解 | #三数之和#
三数之和
https://www.nowcoder.com/practice/345e2ed5f81d4017bbb8cc6055b0b711
using System;
using System.Collections.Generic;
class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param num int整型一维数组
* @return int整型二维数组
*/
public List<List<int>> threeSum (List<int> num) {
// write code here
if (num.Count < 3) return new List<List<int>>();
num.Sort();
List<List<int>> res = new List<List<int>>();
for (int i = 0; i < num.Count - 2; i++) {
for (int j = i + 1; j < num.Count - 1; j++) {
for (int k = j + 1; k < num.Count; k++) {
if (num[i] + num[j] + num[k] == 0) {
List<int> temp = new List<int>();
temp.Add(num[i]);
temp.Add(num[j]);
temp.Add(num[k]);
temp.Sort();
bool flag = false;//有没有重复三元组
foreach (var list in res) {
if (temp[0] == list[0] && temp[1] == list[1] && temp[2] == list[2])
flag = true;
}
if (!flag)res.Add(temp);
}
}
}
}
return res;
}
}

