zoukankan      html  css  js  c++  java
  • (双指针) 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.

    Clarification:

    Confused why the returned value is an integer but your answer is an array?

    Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

    Internally you can think of this:

    // nums is passed in by reference. (i.e., without making a copy)
    int len = removeElement(nums, val);
    
    // any modification to nums in your function would be known by the caller.
    // using the length returned by your function, it prints the first len elements.
    for (int i = 0; i < len; i++) {
        print(nums[i]);
    }

    ------------------------------------------------------------------------------------------------------------------------------------

    这个题如果没有说明"in place" 这个条件的话,也许会更容易,但是,这个已经说明要原地修改数组,也就是要空间复杂度为O(1),于是,我们可以用双指针。我们可以用一个慢指针和快指针,快指针用来从头到尾依次遍历这个原数组,然后用当遍历到不是val的数时,这个数组对应的慢指针指向的索引的数更新,慢指针加一。

    C++代码:

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int k = 0;
            for(int i = 0; i < nums.size(); i++){
                if(nums[i] != val){
                    nums[k] = nums[i];
                    k++;
                }
            }
            return k;
        }
    };
  • 相关阅读:
    php5.5+apache2.4+mysql5.7在windows下的配置
    rsync命令详解
    JVM GC算法 CMS 详解(转)
    JVM1.6 GC详解
    hadoop2升级的那点事情(详解)
    免费SVN空间
    JAVA正则表达式:Pattern类与Matcher类详解(转)
    Eclipse插件安装方式及使用说明
    可扩展Web架构与分布式系统(转)
    关于《Selenium3自动化测试实战--基于python语言》
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10785163.html
Copyright © 2011-2022 走看看