Very simple and optimal c++ solution.


  • 24
    A
    int removeElement(vector<int>& nums, int val) {
        int cnt = 0;
        for(int i = 0 ; i < nums.size() ; ++i) {
            if(nums[i] == val)
                cnt++;
            else
                nums[i-cnt] = nums[i];
        }
        return nums.size()-cnt;
    }

  • 5
    Q

    actually not optimal, suppose there is no item equal to val except the last one, then for first nums.size()-1 item, the code obliviously do useless copy. better to find first item equal to val, then start copy.


  • 0
    G

    Since in that case the cnt will be 0 and nums[i-cnt] = nums[i]; will essentially just be
    nums[ i ] = nums[i];

    I am pretty sure any decent compiler will make it a no-op.


  • 3
    T

    @gbhamra cnt is a run-time variable and the if-else branch check is also run-time, how can compiler know and optimize nums[i-count] = nums[i]?


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

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

    Maybe it is simpler.


  • 0
    M

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

    What's the error of my code!
    THANKS!


Log in to reply
 

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