C# two pointer O(n)


  • 0
    Y
    public class Solution {
        
        
        public int RemoveDuplicates(int[] nums) {
            
            //check null
            if(nums==null)
            {
                return 0;
            }
            
            if(nums.Length==0)
            {
                return 0;
            }
            
            if(nums.Length==1)
            {
                return 1;
            }
                
            //two pointer
            int curr = 0;
            int runner = 1;
            while(runner < nums.Length-1)
            {
                if(nums[runner] != nums[curr])
                {
                    curr += 1;
                    runner += 1;
                    continue;
                }
                    
                while(nums[runner] == nums[curr] && runner < nums.Length-1)
                {
                    runner += 1;
                }
                
                if(nums[runner] != nums[curr])
                {
                    nums[curr+1]=nums[runner];
                    curr += 1;
                }
            }
            
            if(nums[runner] != nums[curr])
            {
                nums[curr+1]=nums[runner];
                curr += 1;
            }
            
            return curr + 1;
            
        }
        
    }

Log in to reply
 

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