27. Remove Element

题目链接:https://leetcode.com/problems/remove-element/

C++解法:

  • 解法一:套用第 26 题的方法(参考:https://leetcode.com/problems/remove-element/discuss/12299/Very-simple-and-optimal-c%2B%2B-solution.)
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int count = 0;
        for (int i = 0; i < nums.size(); ++i) { //注意这里i要从0开始
            if (nums[i] == val)
                count++;
            else
                nums[i-count] = nums[i];
        }
        return nums.size() - count;
    }
};
  • 解法二:升级版(参考:https://leetcode.com/problems/remove-element/discuss/12289/My-solution-for-your-reference.)
class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int begin = 0;
        for (int i = 0; i < nums.size(); ++i) {
            if (nums[i] != val) {
                nums[begin] = nums[i];
                begin++;
            }
        }
        return begin;
    }
};

你可能感兴趣的:(LeetCode,Easy)