C# solution using sorting beats 100% solutions


  • 2
    S
    public class Solution {
        public IList<IList<int>> ThreeSum(int[] nums) {
            var result = new List<IList<int>>();
            
            if (nums.Length < 3)
            {
                return result;
            }
            
            Array.Sort(nums);
            
            for (int first = 0; first < nums.Length - 2; first++)
            {
                int second = first + 1;
                int third = nums.Length - 1;
                
                if (first != 0 && nums[first] == nums[first-1])
                {
                    continue;
                }
                
                while (second < third)
                {
                    //since first is constant in entire loop, if second is also same as previous iteration, then 3rd value will also be same. This will help optimization and removing duplicate results
                    if (second > first + 1 && nums[second] == nums[second-1])
                    {
                        second++;
                        continue;
                    }
                    
                    int sum = nums[first] + nums[second] + nums[third];
                    
                    if (sum == 0)
                    {
                        var triple = new List<int>();
                        triple.Add(nums[first]);
                        triple.Add(nums[second]);
                        triple.Add(nums[third]);
                        result.Add(triple);
                        second++;
                        third--;
                    }
                    else if (sum > 0)
                    {
                        third--;
                    }
                    else
                    {
                        second++;
                    }
                }
            }
            
            return result;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.