如何使用 C# 找到所有加起来等于零的唯一三元组?

简单的方法是我们可以创建三个嵌套循环并一一检查所有三个元素的总和是否为零。如果三个元素的总和为零,则打印元素。

时间复杂度- O(n 3 )

空间复杂度- O(1)

我们可以使用无序集合数据结构来存储数组的每个值。Set 提供了在 O(1) 时间内搜索元素的好处。因此,对于数组中的每一对,我们将查找集合中可能存在的它们总和的负数。如果找到这样的元素,那么我们可以打印三元组,这将是一对整数及其总和的负值。

时间复杂度- O(n 2 )

空间复杂度-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]]

以上是 如何使用 C# 找到所有加起来等于零的唯一三元组? 的全部内容, 来源链接: utcz.com/z/331723.html

回到顶部