[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
numssuch that the firstkelements ofnumscontain the elements which are not equal toval. The remaining elements ofnumsare not important as well as the size ofnums. - Return
k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example & Constraints:
|
|
题目大意
移除数组中元素值等于目标元素,并保证数组的前k个的数值不等于目标元素且出现的顺序与之前前后顺序相同,返回这个数组长度k
题目解决思路
设置初始指针位置为数组索引0位置,遍历整个数组,当数组元素不为目标元素将当前遍历的数组元素赋值给指针索引位置的数组元素同时指针索引向后移动,最后返回这个指针索引即可。
Go 核心代码实现
|
|