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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
这道题和Remove Duplicates from Sorted Array太像了
自己的思路:
int removeElement(int* nums, int numsSize, int val) {
if (numsSize == 0) return 0;
int i = 0, j;
for (j = 0; j < numsSize; j++) {
nums[i] = nums[j];
if (nums[i] != val)
i++;
}
return i;
}
beats 28.42%,第一句可以删掉
精简一下,效率不变
int removeElement(int* nums, int numsSize, int val) {
int i = 0, j;
for (j = 0; j < numsSize; j++) {
if (nums[j] != val)
nums[i++] = nums[j];
}
return i;
}
思考:
if的判断语句应该用什么?
for中的 j 的边界?
想清楚可减少代码量
知识点:
i++和++i -----------> 后自加和前自加