C# fast solution with explanation


  • 0
    E
    public int RemoveElement(int[] nums, int val) {
        int head = 0;
        int tail = nums.Length - 1;
        
        while (tail >= head)
        {
            if (nums[head] != val)
                head++;
            else
            {
                var tmp = nums[tail];
                nums[tail] = val;
                nums[head] = tmp;
                tail--;
            }
        }
        
        return tail + 1;
    }
    

    Basically the idea is to move unwanted elements to the end. While iterating through the array (from head), check if the unwanted element is in head position. If so, move it to the end of the array (tail) and decrement the tail index. If it is not in head position, increment the head pointer. Do this while tail is bigger than or equal to head. At the end return tail + 1 since question wants the length not the index.


Log in to reply
 

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