赞
踩
https://leetcode.cn/problems/remove-element/
class Solution { public int removeElement(int[] nums, int val) { int count=0; int[] index=new int[100]; for(int i=0;i<nums.length;i++){ if(nums[i]==val){ count++; index[count]=i; } } int count1=count; for(int i=nums.length-count;i<nums.length;i++){ if(nums[i]==val){ count1--; } } for(int i=nums.length-count;i<nums.length;i++){ if(nums[i]!=val){ nums[index[count1--]]=nums[i]; nums[i]=val; } } return nums.length-count; } }
等于快慢指针法
class Solution {
public int removeElement(int[] nums, int val) {
// 快慢指针
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
if (nums[fastIndex] != val) {
nums[slowIndex] = nums[fastIndex];
slowIndex++;
}
}
return slowIndex;
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。