zoukankan      html  css  js  c++  java
  • [Leetcode 2] 27 Remove Element

    Problem:

    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.

    Analysis:

    Use two pointers, ptrA points to the next-valid-to-copy place; ptrB go through the input array, if *ptrB equals the given value K, skip this position else copy it to *(++ptrA) position. Considering some special case: 1. A=[], K=anyValue, need to return 0; 2. A=[k, k, k] K=k, need to return 0;

    The time complexity is O(n) and the space complexity is O(n)

    Code:

    public class Solution {
        public int removeElement(int[] A, int elem) {
            // Start typing your Java solution below
            // DO NOT write main() function
            //if (A.length == 0) return 0;
            
            int a=0;
            for (int b=0; b<A.length; b++) {
                if (A[b] != elem) {
                    A[a++] = A[b];
                }
            }
            
            return a;
        }
    }

    Attention:

    Since here A always point to the next-to-copy place, the special case A = [] can be merged into the general solution

  • 相关阅读:
    input标签上传文件处理。
    Radio单选框元素操作。
    CompletableFuture方法
    传播学 2
    传播学 1
    0
    紅軍不怕遠征難
    ~~~~~~~~~
    什么是企业战略
    论述提供公共咨询服务的两种主要方式。
  • 原文地址:https://www.cnblogs.com/freeneng/p/3002351.html
Copyright © 2011-2022 走看看