标签:leetcode
Remove Element
Given an array and a value, remove all instances of that value in place and return the new length.
The order of elements can be changed. It doesn‘t matter what you leave beyond the new length.
给一个数组和一个val,删除所有与val相等的数, 并返回新数组的长度n。class Solution { public: int removeElement(vector<int>& nums, int val) { int n = nums.size(),num = 0; for (int i = 0;i < n;i++) { if (nums[i] == val) num++; else { nums[i - num] = nums[i]; } } return n - num; } };
class Solution { public: int removeElement(vector<int>& nums, int val) { int n = nums.size(),ans = 0; // ans 为不等于val的个数 for (int i = 0;i < n;i++) { if (nums[i] != val) { // 如果不等于val,就将nums[i]赋给第ans个数 ,并且ans++ nums[ans++] = nums[i]; } } return ans; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/u014705854/article/details/46916793