題目: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 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.
Example:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of num
題目要求:不要爲其他數組分配額外的空間,您必須通過在 O(1)額外的內存中就地修改輸入數組來完成此操作。
分析:題目已經說了我們不能使用額外的空間,也就是說我們不能創建新的數組來拷貝這個數組,且題目要求只是返回數組的長度,其實很容易想到,直接if判斷,創建有一個index來計數就ok。最開始我就就想錯了。。。。一直想着創建新的數組或者其他東西來保存。
Java實現代碼:
public int removeElement(int[] nums, int val) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i]!=val) {
nums[++index] = nums[i];
}
}
return index;
}