zoukankan      html  css  js  c++  java
  • [LeetCode] #27 Remove Element

    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.

    首先标记初始位置flag,然后统计与val相同的个数,之后删除相同元素即可。时间4ms,代码如下:

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            if (nums.empty())
                return 0;
            sort(nums.begin(), nums.end());
            int n = nums.size(), len=n;
            int flag = -1;
            for (int i = 0, j = 0; i < n; i++){
                if (nums[i] == val){
                    len--;
                    if (flag==-1)
                        flag = i;
                }
            }
            if (len != n)
            for (size_t i = 0; i < n - len;++i)
                nums.erase(nums.begin() + flag);
            return len;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    团队冲刺第五天
    每日学习
    团队冲刺第四天
    团队冲刺第三天
    每日学习
    2021.4.12
    2021.4.10
    2021.3.18
    2021.3.15
    2021.3.14
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4570369.html
Copyright © 2011-2022 走看看