首页 > 其他 > 详细

Remove Element - LeetCode

时间:2019-02-03 14:08:48      阅读:162      评论:0      收藏:0      [点我收藏+]

题目链接

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函数太好用了!

Remove Element - LeetCode

原文:https://www.cnblogs.com/multhree/p/10350268.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!