一 題目
二 思路(僅解釋方案1 更優(yōu)解)
解析題目意思矾湃,其實(shí)就是想把所有不同的元素放在前面稠茂,
那么我們可以計(jì)數(shù)k為不同元素的數(shù)量,那么0~k-1位均不等于val,k位元素為當(dāng)前需要重新設(shè)置新的不同值的下標(biāo)哄辣。*
三代碼:
方案1
class Solution {
public static int removeElement(int[] nums, int val) {
int k=0;
for (int i = 0; i < nums.length; i++) {
//如果不同
if (nums[i]!=val){
k++;
//前res-1位數(shù)均已安排為不同數(shù)
nums[k-1]=nums[i];
}
}
return k;
}
}
方案2
class Solution {
public int removeElement(int[] nums, int val) {
int res=0;
Queue<Integer> sameIndex=new ArrayDeque<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i]==val){
sameIndex.add(i);
} else {
res++;
if (!sameIndex.isEmpty()){
nums[sameIndex.poll()]=nums[i];
sameIndex.add(i);
}
}
}
return res;
}
}