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     }
  • 相关阅读:
    关于JVM的一些想法
    hashMap理解以及jdk1.7、jdk1.8其中区别
    各数据库如何实现自增
    dubbo遇坑记录
    mysql建表语句问题
    @Configuration
    生成一个唯一的ID
    门面模式
    关于getClass().getClassLoader()
    元素链
  • 原文地址:https://www.cnblogs.com/feiling/p/3209850.html
Copyright © 2011-2022 走看看