Move as few elements as possible


  • 0
    A

    Given an array of size K (e.g. 1000), if only N (e.g. 5) elements need to be deleted, then at most N write operations are issued.

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int b = 0, e = nums.size() - 1;
            while (1) {
                for (; b <= e && nums[b] != val; b++);
                for (; b <= e && nums[e] == val; e--);
                if (b > e) break;
                nums[b++] = nums[e--];
                }
            return b;
        }
    };
    

Log in to reply
 

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