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

  • 相关阅读:
    配置文件管理
    Nacos学习
    dockerCompose学习
    Dockerfile
    vue生命周期
    github使用
    推荐系统
    js笔记17
    js笔记16
    js笔记15
  • 原文地址:https://www.cnblogs.com/freeneng/p/3002351.html
Copyright © 2011-2022 走看看