标签:for size att return ant 移动 hang his other
Description:
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.
解题思路:
由于题目里面说明元素的顺序可以调换,并且超出新数组中超过新长度的部分不用予以理会,
因此这里的remove并不一定要将这个元素从数组中删除,可以把不等于val值的数提到前面来。
count用来累积目前遍历到的不等于val值(也就是不需要移动的元素)的数目,
因此在每次遍历的时候将下标为i的对应值赋值到下标为count的位置(nums[count] = nums[i];)即可。
代码:
class Solution { public: int removeElement(vector<int>& nums, int val) { int count = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] != val) { nums[count] = nums[i]; count++; } } return count; } };
标签:for size att return ant 移动 hang his other
原文地址:http://www.cnblogs.com/SYSU-Bango/p/7542690.html