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

1632

Leave a Reply

Name and Email Address are required fields.
Your email will not be published or shared with third parties.