zoukankan      html  css  js  c++  java
  • LeetCode Remove Element

    1.题目

    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.


    2.解决方式


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

    思路:题目的意思比較简单就是数组中删除一些元素,跟输入的值一样,然后返回数组长度。普通情况下数组中删除一个元素,后面的所有元素都要往前面移,非常慢的。但题目中说,数组内的内容能够任意更改。所以能够用一种比較快的方式删除,就是不删除,直接与最后一个元素交换,然后缩小数组长度。

    http://www.waitingfy.com/archives/1632

  • 相关阅读:
    ZOJ 3556
    ZOJ 2836
    HDU 2841
    HDU 4135
    POJ 3695
    POJ 2773
    HDU 4407
    HDU 1796
    ZOJ 3688
    ZOJ 3687
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/4514537.html
Copyright © 2011-2022 走看看