• leetcode 27. Remove Element


    Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

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

    Example 1:

    Given nums = [3,2,2,3], val = 3,
    
    Your function should return length = 2, with the first two elements of nums being 2.
    
    It doesn't matter what you leave beyond the returned length.
    

    Example 2:

    Given nums = [0,1,2,2,3,0,4,2], val = 2,
    
    Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
    
    Note that the order of those five elements can be arbitrary.
    
    It doesn't matter what values are set beyond the returned length.

    题目大意:给定一个数组,一个值,返回删除数组中与这个值相等的元素后的数组的长度。要求:实现in-place操作,不另外新开辟空间

    思路一:双指针。

    1 int removeElement(vector<int>& nums, int val) {
    2         int i = 0;
    3         for (auto num : nums) {
    4             if (num != val) {
    5                 nums[i++] = num;
    6             }
    7         }
    8         return i;
    9     }

    思路二:双指针,一头一尾, 类似快排,左指针直到指向等于val的索引为止,右指针直到指向不等于val的索引为止。

     1 int removeElement(vector<int> &nums, int val) {
     2         int i = 0, j = nums.size();
     3         while (i < j) {
     4             while ((i < j) && nums[i] != val) ++i;
     5             while ((i < j) && nums[j - 1] == val) --j;
     6             if (i < j)
     7                 swap(nums[i], nums[j - 1]);
     8         }
     9         return i;
    10     }
  • 相关阅读:
    avrdude: stk500_getsync(): not in sync: resp=0x00
    PCB封装技术
    C/C++基础问题归集
    mf210v 端口的映射
    alsamixer 在音频子系统的使用
    rp2836 网卡以及串口与接插件位置关系
    RP2837 IN1-IN2 对应关系 2路DI
    RP2837 OUT1-OUT2 对应关系 2路DO
    RP2836 板卡信息标识
    RP2836 OUT0-OUT7 对应关系
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11840058.html
Copyright © 2020-2023  润新知