問題:
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.
大意:
給出一個(gè)數(shù)組和一個(gè)數(shù),移除數(shù)組中所有等于該數(shù)的值并返回新長度。
不要使用額外的空間來創(chuàng)建另一個(gè)數(shù)組,你必須在恒定的內(nèi)存中做。
元素的順序可以改變。新長度以外的內(nèi)容無所謂是什么樣子。
思路:
這道題的要求在于不創(chuàng)建新數(shù)組,而是在原有的數(shù)組內(nèi)容來進(jìn)行操作,按題目的意思就是將所有不等于那個(gè)值的數(shù)放到數(shù)組前面,然后返回這些數(shù)的數(shù)量,也就是數(shù)組的一個(gè)長度,這個(gè)長度后面的數(shù)是什么樣子的都沒有關(guān)系。
按照這個(gè)思路很明顯就是檢測(cè)如果不一樣就放到前面來了。我們弄兩個(gè)指針,一個(gè)遍歷數(shù)組中的數(shù),一個(gè)記錄不一樣的數(shù)的數(shù)量,那么記錄數(shù)量的數(shù)一定是小于等于遍歷的那個(gè)指針數(shù)的,所以每當(dāng)遍歷到不一樣的數(shù)時(shí),就放在數(shù)組中記錄不一樣的數(shù)的位置,因?yàn)榈诙€(gè)指針一定是不會(huì)大于第一個(gè)數(shù)的,所以不會(huì)存在覆蓋一些沒遍歷到的數(shù)的問題,這相當(dāng)于是把不一樣的數(shù)都集中到數(shù)組前面了,等遍歷完了,后面的數(shù)其實(shí)還是保持原樣的,跟題目要求的很契合。
代碼(Java):
public class Solution {
public int removeElement(int[] nums, int val) {
int position = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[position] = nums[i];
position++;
}
}
return position;
}
}
合集:https://github.com/Cloudox/LeetCode-Record