zoukankan      html  css  js  c++  java
  • 【LeetCode】27. Remove Element (2 solutions)

    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.

    解法一:

    常规做法,设置一个新A数组的下标ind。

    遍历过程中遇到elem就跳过,否则就赋给新A数组下标对应元素。缺点是有多余的赋值。

    class Solution {
    public:
        int removeElement(int A[], int n, int elem) {
            int ind = 0;
            for(int i = 0; i < n; i ++)
            {
                if(A[i] != elem)
                    A[ind ++] = A[i];
            }
            return ind;
        }
    };

    解法二:最优美的解法,当遍历过程中遇到elem,就用末尾的元素来填补。

    这样甚至遍历不到一次。

    注意:从末尾换过来的可能仍然是elem,因此i--,需要再次判断。

    class Solution {
    public:
        int removeElement(int A[], int n, int elem) 
        {
            int newlength = n;
            for(int i = 0; i < newlength; i ++)
            {
                if(A[i] == elem)
                {
                    A[i] = A[newlength-1];
                    i--;
                    newlength--;
                }
            }
            return newlength;
        }
    };

  • 相关阅读:
    Unity 预处理命令
    Unity 2DSprite
    Unity 生命周期
    Unity 调用android插件
    Unity 关于属性的get/set
    代码的总体控制开关
    程序员怎么问问题?
    VCGLIB 的使用
    cuda实践(1)
    python之json文件解析
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3762932.html
Copyright © 2011-2022 走看看