题目描述:

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 by modifying the input array in-place with O(1) extra memory.

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

本题的要求是:给我们一个数和数组,让我们移除数组中的这个数并返回新数组的长度。而且不能分配新的空间给数组,超出数组长度还有数是没有关系的。(例:要求返回的是{2,3},但返回的是{2,3,1}也是无所谓的)。

例子:

1 Given nums = [3,2,2,3], val = 3,
2 
3 Your function should return length = 2, with the first two elements of nums being 2.

 

解题思路:

这题的思路比较简单,只要将数组中的数与要求移除的数进行逐一比较,将不同的数移到数组前面覆盖相同的数即可。

代码:

1 int removeElement(int* nums, int numsSize, int val) {
2     int count=0;
3     for(int i=0;i<numsSize;i++){
4         if(nums[i]!=val){
5             nums[count++]=nums[i];
6         }
7     }
8     return count;
9 }

 

posted on 2018-02-01 11:12  宵夜在哪  阅读(82)  评论(0编辑  收藏  举报