leetcode 27. Remove Element

来源:互联网 发布:mac电脑转换视频格式 编辑:程序博客网 时间:2024/06/07 07:15

题目描述:

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3]val = 3

Your function should return length = 2, with the first two elements of nums being 2.

解题思路:

利用两个指针,用类似于快排的partition函数的处理方法来处理:

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int len = 0;        for(int index = 0; index < nums.size(); index++){            if(nums[index] != val)                nums[len++] = nums[index];        }        return len;    }};
空间复杂度为O(1),时间复杂度为O(n),这种方法是挺好的,所用时间为4ms,但当等于val的数字很少,这样做还是会导致出现很多不必要的赋值操作。

所以,可以用一前一后两个指针,时空复杂度还是一样,运行时间也是4ms,不过在val出现次数很少的情况下,确实能够减少赋值操作次数,但相反的,如果val出现次数增多的时候,赋值操作就会相应地增多,这也是种权衡了。。但注意,如果对于末尾的指针处理方式像快排的partition函数那样具体,时间可能会变为8ms,下面是一种实现方式:

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int len = 0, last = nums.size()-1;        while(len <= last){            if(nums[len] != val)                ++len;            else                nums[len] = nums[last--];        }        return len;    }};

8ms代码:

class Solution {public:    int removeElement(vector<int>& nums, int val) {        int len = 0, last = nums.size()-1;        while(len <= last){            if(nums[len] != val)                ++len;            else{                if(nums[last] == val)                    --last;                else                    swap(nums[len], nums[last]);            }        }        return len;    }};


参考:leetcode题解



1 0
原创粉丝点击