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;
        }
    };

  • 相关阅读:
    尝试一下搭博客
    python IO
    python OOP
    杂笔记
    codeforces 217E 【Alien DNA】
    dfs序七个经典问题(转)
    poj 1945 Power Hungry Cows A*
    NOIP 2012 洛谷P1081 开车旅行
    洛谷 P1924 poj 1038
    poj 2176 folding
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3762932.html
Copyright © 2011-2022 走看看