leetcode #27 in cpp

This problem is to remove all instances equal to a given value, called 'val',  in the array. The array could be out of order. 

Solution: 

           We know that in the end we would have every element that's not equal to val in the array. How would we put those elements? Suppose we have 3,3,3,3,1,2,4,3,5, and val = 3. The final result should be 1,2,4,5. Note that before we meet 1, we have 4 3s, this means if we remove those 3s, 1 is going to be shifted to left by 4 steps. also 2, 4 should be shifted by 4 steps. For 5, there are 5 3s before it, and thus 5 should be shifted to left by 5 steps. Now we can see that, we should shift the element not equal to val by the number of val at its left. So we scan through the array, and keep counting how many val we have met. Once we have that count, we could shift every element correctly. 

Code: 

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值