如何使用 C# 查找所有加起来等于零的唯一三元组?
简单的方法是,我们可以创建三个嵌套循环,逐一检查所有三个元素的和是否为零。如果三个元素的和为零,则打印这些元素。
时间复杂度 − O(n3)
空间复杂度 − O(1)
我们可以使用无序集合数据结构来存储数组的每个值。集合提供了在 O(1) 时间内搜索元素的优势。因此,对于数组中的每一对,我们将查找其和的负数,该负数可能存在于集合中。如果找到这样的元素,那么我们可以打印三元组,它将是整数对及其和的负值的组合。
时间复杂度 − O(n2)
空间复杂度 − O(n)
示例
public class Arrays{
public List<List<int>> ThreeSum(int[] nums){
List<List<int>> res = new List<List<int>>();
if (nums == null || nums.Length == 0){
return res;
}
var newnums = nums.OrderBy(x => x).ToArray();
for (int i = 0; i < newnums.Count(); i++){
int left = i + 1;
int right = newnums.Count() - 1;
while (left < right){
int sum = newnums[i] + newnums[left] + newnums[right];
if (sum == 0){
List<int> l = new List<int>();
l.Add(newnums[i]);
l.Add(newnums[left]);
l.Add(newnums[right]);
res.Add(l);
int leftValue = newnums[left];
while (left < newnums.Length && leftValue == newnums[left]){
left++;
}
int riightValue = newnums[right];
while (right > left && riightValue == newnums[right]){
right--;
}
}
else if (sum < 0){
left++;
}
else{
right--;
}
}
while (i + 1 < newnums.Length && newnums[i] == newnums[i + 1]){
i++;
}
}
return res;
}
}
static void Main(string[] args){
Arrays s = new Arrays();
int[] nums = { -1, 0, 1, 2, -1, -4 };
var ss = s.ThreeSum(nums);
foreach (var item in ss){
foreach (var item1 in item){
Console.WriteLine(item1);
}
}
}输出
[[-1,-1,2],[-1,,0,1]]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP