A simple C++ code (4ms) left/right pointers used

  • 0

    Do it like quicksort.
    Use a left pointer to track the last element found that is equal to val (scanned from the left) and right to track the last element that is not equal to val. Then swap left/right

    class Solution {
        int removeElement(vector<int>& nums, int val) {
            int left= 0, right=nums.size()-1;
                if(nums[left] != val) ++left;
                else if(nums[right] == val) --right;
                else swap(nums[left++], nums[right--]);
            return left; 

Log in to reply

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