3SUM without duplicates c#


  • 0
    A
    public class Solution
    {
            public IList<IList<int>> ThreeSum(int[] nums)
            {
                if (nums == null) return null;
                
                var result = new List<IList<int>>();
    
                Array.Sort(nums);
    
                for (int i = 0; i < nums.Length - 2; i++)
                {
                    if (nums[i] > 0) return result; // optimization
                    
                    if (i > 0 && nums[i] == nums[i-1]) continue; // avoid duplicates
                        
                    int l = i + 1;
                    int r = nums.Length - 1;
    
                    while (l < r)
                    {
                        int sum = nums[i] + nums[l] + nums[r];
    
                        if (sum == 0)
                        { 
                            result.Add(new List<int>() { nums[i], nums[l], nums[r] });
                            
                            l++;
                            r--;
                            
                            while (l < r && nums[l] == nums[l-1]) // avoid duplicates
                            {
                                l++;
                            }
                            
                            while (l < r && nums[r] == nums[r+1]) // avoid duplicates
                            {
                                r--;
                            }
                        }
                        else if (sum < 0)
                        {
                            l++;
                        }
                        else
                        {
                            r--;
                        }                    
                    }
                }
    
    
                return result;
            }
    }
    
    

Log in to reply
 

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