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
  • 相关阅读:
    Java 字符串判空
    JavaScript try catch 常用场景(一)
    IE console 未定义
    共享锁与排它锁
    js 原型链
    js的原型模式
    js中RegExp类型
    js中Array对象方法详解
    js动态生成input指定My97DatePicker时间问题
    利用spring、cxf编写并发布webservice
  • 原文地址:https://www.cnblogs.com/immjc/p/7417925.html
Copyright © 2011-2022 走看看