您的位置:首页 > 其它

Leetcode[27]-Remove Element

2015-06-09 09:54 330 查看
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.

思路:遍历数组,如果数组对应的数等于给定的值,数组最后一位和当前位互换,然后将数组长度减一;否则,就执行i++;最后重置数组长度。

Code(c++):

class Solution {
public:

    void swap(int *a, int *b){
        int temp = *a;
        *a = *b;
        *b = temp;
    }
    int removeElement(vector<int>& nums, int val) {
        int n = nums.size();
        if(n == 0) return 0;
        int i = 0;
        while( i < n){
            if(nums[i] == val) {
                swap(&nums[i],&nums[n-1]);
                n--;
            }else{
                i++;
            }
        }
        nums.resize(n);
        return n;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: