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

  • 相关阅读:
    py3学习笔记0(入坑)
    为什么很多PHP文件最后都没有?>
    作业
    凯撒密码、GDP格式化输出、99乘法表
    作业4
    作业3
    turtle库基础练习
    作业2
    作业1
    编译原理有限自动机的构造与识别
  • 原文地址:https://www.cnblogs.com/freeneng/p/3002351.html
Copyright © 2011-2022 走看看