LeeCode from 0 ——27. Remove Element

27. Remove Element

Given an array nums and a value val, 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.

解题思路:

1)数组长度为0以及长度为1且唯一元素等于val时,返回0;

2)数组长度为1,且唯一元素不等于val时,返回1,否则进入3);

3)判断数组内每个元素是否等于val,不等于时,存入nums[j]中,等于时则i加1继续循环;

代码如下:

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n=nums.size();
int j=0;
if(n==0 ||(n==1 && nums[0]==val))
return 0;
else if(n==1)
return 1;
else{
int i=0;
while(i<n){
if( nums[i]!=val){
nums[j]=nums[i];
j++;
i++;
}
else
i++;
}
}
return j;


}
};

猜你喜欢

转载自www.cnblogs.com/ssml/p/9178032.html