27. Remove Element
Given an integer array nums
and an integer val
, remove all occurrences of val
in nums
in-place. The order of the elements may be changed. Then return the number of elements in nums
which are not equal to val
.
Consider the number of elements in nums
which are not equal to val
be k
, to get accepted, you need to do the following things:
- Change the array
nums
such that the firstk
elements ofnums
contain the elements which are not equal toval
. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
class Solution {
public int removeElement(int[] nums, int val) {
int n = nums.length;
int count = 0;
for(int i = 0;i<n;i++){
if(nums[i] != val){
nums[count] = nums[i];
count++;
}
}
return count;
}
}
Comments
Post a Comment