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
  • 相关阅读:
    下载程序的疑问
    Beaglebone环境建立:电源适配器供电+网线ssh
    Android百分比布局支持库介绍——com.android.support:percent
    android应用中去掉标题栏的方法
    自己写的进度条
    返回图片指定点的RGB值
    修改指定图片的分辨率
    跨域访问的问题和解决过程
    C#取硬盘、CPU、主板、网卡的序号 ManagementObjectSearcher
    Sql Server字符串函数
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12935957.html
Copyright © 2011-2022 走看看