Leetcode 27. Remove Element

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.

Hint:

    1. Try two pointers.
    2. Did you use the property of "the order of elements can be changed"?
    3. What happens when the elements to remove are rare?

思路:比较容易想到的是初始化新长度pos为0,每当遍历到的元素不为val值,则将他放在pos位置,pos++。比如这个例子pos = 0, i = 0 开始,由于nums[i] == val,所以不操作,nums[1] != val,所以nums[pos](pos = 0) = nums[1],pos++; nums[2] != val,所以nums[pos] = nums[2](pos = 1),pos++;nums[3] == val,不进行赋值操作。最终pos = 2;

 

 1 class Solution {
 2 public:
 3     int removeElement(vector<int>& nums, int val) {
 4         int pos = 0, i, len = nums.size();
 5         for(i = 0; i < len; i++){
 6             if(nums[i] != val){
 7                 nums[pos] = nums[i];
 8                 pos++;
 9             }
10         }
11         return pos;
12     }
13 };

 

在C++ vector中有erase()这个函数,所以每当nums[i] == val,就可以将其删除。

 1 class Solution {
 2 public:
 3     int removeElement(vector<int>& nums, int val) {
 4         for(vector<int>::iterator it = nums.begin(); it != nums.end();){
 5             if(*it == val)
 6                 it = nums.erase(it);
 7                 //这里不能写成nums.erase(it);在erase后,it失效,并不是指向vector的下一个元素,it成了一个“野指针”。
 8             else
 9                 it++;
10         }
11         return (int)nums.size();
12     }
13 };

注意到题目所说"the order of elements can be changed",(我没想到这样做。。。学习了别人的代码,如下):思想就是从下标0开始,如果nums[i] == val,则将nums[i]

 

和数组最后一个元素交换,同时数组长度减1,相当于把这个数排除了。否则比较nums[i+1]和val.

 

 1 class Solution {
 2 public:
 3     int removeElement(vector<int>& nums, int val){
 4         int n = nums.size();
 5         for(int i = 0; i < n;){
 6             if(nums[i] == val){
 7                 swap(nums[i], nums[n - 1]);
 8                 n--;
 9             } else {
10                 i++;
11             }
12         }
13         return n;
14     }
15 };

 

posted @ 2016-09-03 22:06  琴影  阅读(220)  评论(0编辑  收藏  举报