LeetCode #27 – Remove Element [数组操作]

Link

点击打开题目链接

Problem

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Mean

给你一个整数数组,让你删除值为val的元素。

Analysis

复杂度要限制在O(N)内,扫一遍数组保留跟val不同的数即可。

C++ code

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

欢迎留言