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.

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

    思路:

    两层循环,注意删除元素时指针要回溯,此方法的时间复杂度为O(n^2)

     1 public class Solution {
     2     public int removeElement(int[] A, int elem) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int len = A.length;
     6         for(int i = 0; i < len;){
     7             if(A[i] == elem){
     8                 for(int j = i + 1; j < len; j++){
     9                     A[j - 1] = A[j];
    10                 }
    11                 len --;
    12                 continue;
    13             }
    14             i++;
    15         }
    16         return len;
    17     }
    18 }

    双指针,时间复杂度为O(n)

     1 public int removeElement(int[] A, int elem) {
     2         int len = A.length;
     3         int cur = 0;
     4         for(int i = 0; i < len; i ++){
     5             if(A[i] == elem)
     6                 continue;
     7             
     8             A[cur] = A[i];
     9             cur ++;
    10         }
    11         return cur;
    12     }
  • 相关阅读:
    WPS JS宏
    WPS基础
    算法文章收藏
    辩论赛
    物流系统
    C#导出excel复杂表格(单元各合并)
    VUE复杂表格合并
    Linux系统创建一个npm命令行工具
    Java使用技巧记录
    Ubuntu系统安装nodejs及npm
  • 原文地址:https://www.cnblogs.com/feiling/p/3209850.html
Copyright © 2011-2022 走看看