zoukankan      html  css  js  c++  java
  • 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.

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [一句话思路]:

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [算法思想:迭代/递归]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

     [潜台词] :

    class Solution {
        public int removeElement(int[] nums, int val) {
            int index = 0;
            
            //边界情况
            if (nums == null || nums.length == 0) {
                return 0;
            }
            
            
            for (int num : nums) {
                if (num != val) {
                    nums[index++] = num;
                }
            }
    
            return index;
        }
    }
    View Code
  • 相关阅读:
    jquery实现checkbox列表的全选不选
    SQL server 无法更新标识列
    如何设置IIS程序池的回收时间,才能最大程度的减少对用户的影响?
    混合式App开发 Apicloud 官方iPhone X 适配
    C# 加密解密以及sha256不可逆加密案例
    C#排队处理DEMO
    vs中如何统计整个项目的代码行数
    ApiCloud利用NVTabBar模块快速搭建起APP的框架
    走进异步编程的世界--async/await项目使用实战
    H5开发APP考题和答案
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12935957.html
Copyright © 2011-2022 走看看