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     }
  • 相关阅读:
    TinyOS功率编程指南
    深度学习入门资料
    通信常识
    CTF入门
    前端开发工具之服务器选择
    Spring
    NoSQL -- MongoDB
    NoSQL -- Redis
    mysql alter table修改表结构添加多个字段的几个写法
    gongle 访问助手安装
  • 原文地址:https://www.cnblogs.com/feiling/p/3209850.html
Copyright © 2011-2022 走看看