Clean simple fast C++ solution


  • 0
    S

    I delet element from vector in O(1) swap with last + pop_back.
    As we can see the constraction of vector isn't broke like in other solutions.

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            for (int i = 0; i < nums.size(); ++i) {
                if (nums[i] == val) {
                    swap(nums[i], nums[nums.size() - 1]);
                    nums.pop_back();
                    --i;
                }
            }
            return nums.size();
        }
    };
    

Log in to reply
 

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