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

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

    Do not allocate extra space for another array, you must do this in place with constant memory.

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

    Example:
    Given input array nums = [3,2,2,3]val = 3

    Your function should return length = 2, with the first two elements of nums being 2.

    返回删除元素后的数组长度,使用迭代器操作中的erase来删除元素即可,erase返回删除元素的下一个位置的迭代器。使用erase后元素彻底被删除,所以数组的大小变成删除元素后的数组大小。

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

    使用双指针来遍历数组,如果头指针指向的元素和目标值相等,则将尾指针的值赋给头指针元素,然后尾指针向前移动一位,头指针继续判断该位置元素是否和目标值相同。

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int n = nums.size();
            for (int i = 0; i != n; i++) {
                if (nums[i] == val) {
                    nums[i] = nums[n - 1];
                    n--;
                    i--;
                }
            }
            return n;
        }
    };
    // 6 ms
  • 相关阅读:
    +-字符串
    心急的C小加
    明明的随机数
    最大公约数和最小公倍数
    独木舟上的旅行
    背包问题
    喷水装置
    奇数魔方
    栈的应用
    c链表结点的删除和添加
  • 原文地址:https://www.cnblogs.com/immjc/p/7417925.html
Copyright © 2011-2022 走看看