LeetCode-15.3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.

    For example, given array S = {-1 0 1 2 -1 -4},

    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

public class Solution {
    public IList<IList<int>> ThreeSum(int[] nums)
    {
         Array.Sort(nums);
            IList<IList<int>> result = new List<IList<int>>();
            IList<int> list;
            int front, back;
            for (int i = 0; i < nums.Length-2; i++)
            {
                int target = -1 * nums[i];
                front = i + 1;
                back = nums.Length - 1;
                while (front<back)
                {
                    if (nums[front]+nums[back]>target)
                    {
                        back--;
                    }
                    else if (nums[front] + nums[back] < target)
                    {
                        front++;
                    }
                    else
                    {
                        list = new List<int>();
                        list.Add(-1 * target);
                        list.Add(nums[front]);
                        list.Add(nums[back]);
                        result.Add(list);

                        while (front<nums.Length-1&& nums[front]== nums[front+1])
                        {
                            front++;
                        }
                        front++;

                        while (back >i+1 && nums[back] == nums[back - 1])
                        {
                            back--;
                        }
                        back--;

                        while (i< nums.Length - 1&&nums[i] == nums[i + 1])
                            i++;
                    }
                }
            }
            return result;
    }
}


你可能感兴趣的:(LeetCode,算法)