Remove Element - LeetCode

题目链接

Remove Element - LeetCode

注意点

  • 输入的数组是无序的

解法

解法一:使用了erase函数,将等于val的值移除。时间复杂度为O(n)

class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        for(auto it = nums.begin();it != nums.end();)
        {
            if(*it == val) it = nums.erase(it);
            else it++;
        }
        return nums.size();
    }
};

解法二:来自官方题解。将不等于val的值移到前面。时间复杂度为O(n)

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

小结

  • c++的stl函数太好用了!

猜你喜欢

转载自www.cnblogs.com/multhree/p/10350268.html