码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Element

时间:2018-03-20 22:53:06      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:wiki   you   org   beyond   and   remove   href   bsp   targe   

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.

Example:

Given nums = [3,2,2,3], val = 3,

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

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

 

Remove Element

标签:wiki   you   org   beyond   and   remove   href   bsp   targe   

原文地址:https://www.cnblogs.com/jiadyang/p/8613126.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!