LeetCode-ThreeSum

LeetCode-ThreeSum

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != ji != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

Constraints:

  • 3 <= nums.length <= 3000
  • -105 <= nums[i] <= 105
using System;
using System.Collections.Generic;

public class ThreeSumSolution
{
    public IList<IList<int>> ThreeSum(int[] nums)
    {
        if (nums.Length < 3) return new List<IList<int>>();
        Array.Sort(nums);

        IList<IList<int>> result = new List<IList<int>>();
        for (int i = 0; i < nums.Length - 2; i++)
        {
            var j = i + 1; //left
            var k = nums.Length - 1; //right
            //排序後,每次 第一位取出來的時候,若後面的值跟前面一樣,代表 前面就循環過了,就不再比較一次 ,直接跳下一個
            //ex [1, 1, 2, 3, 4]
            // 若i=1,值是1,但i=0已經比較過 值是1的,所以SKIP
            if (i > 0 && nums[i] == nums[i - 1]) continue; 
            
            //雙指針
            while (j < k)
            {
                //ex [1, 1, 2, 3, 4]
                // i = 0, 這時j是1,k是3,兩兩 與第i項加總
                
                var sum = nums[i] + nums[j] + nums[k];
                if (sum == 0) //若剛好=0,是我們要的組合
                {
                    result.Add(new List<int>() {nums[i], nums[j], nums[k]});
                    while (j < k && nums[j] == nums[j + 1]) j++; //因為排過序,判斷 往右 是 不是一樣的數字,若是一樣的數字就 再++往右跳過
                    while (j < k && nums[k] == nums[k - 1]) k--; //因為排過序,判斷 往左 是 不是一樣的數字,若是一樣的數字就 再--往左跳過

                    //上面的小while只是累加到重覆的那一個位置 下面還是要再各別往內逼近
                    j++;
                    k--;
                }
                else if (sum < 0)
                {
                    //因為排序過,因此若和小於0,代表 需要從中間數往右找更大的數字看看,所以左指針++
                    j++;
                }
                else
                {
                    //因為排序過,因此若和大於0,代表 需要從最右的大數往左找更小的數字看看,所以右指針--
                    k--;
                }
            }
        }

        return result;
    }
}

using FluentAssertions;
using NUnit.Framework;

public class ThreeSumTests
{
    [SetUp]
    public void Setup()
    {
    }

    [Test]
    public void Test001()
    {
        ThreeSumSolution ts = new ThreeSumSolution();
        var result = ts.ThreeSum(new[] {-1, 0, 1, 2, -1, -4});
        result.Count.Should().Be(2);
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *