C++ 4ms, two solutions


  • 0

    general solution

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

    if the elements to remove are rare

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

    Judging by running speed, the second algo is not necessary better than the first one even if the elements to remove are rare. However, it preserves the best of original sequence.


Log in to reply
 

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