题目
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.
解
public class Solution {
public int removeElement(int[] nums, int val) {
int count1=0;
for(int k=0;k<nums.length;k++){
if(nums[k]==val)
count1++;
}
if(count1==nums.length)
return 0;
int i=0;
int j=nums.length-1;
int temp=0;
int count=0;
while(i<j){
if(nums[j]==val){
count++;
j--;
//System.out.println("count:"+count);
}else
{
if(nums[i]==val){
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
count++;
j--;
}else{
i++;
}
}
}
//System.out.println("count:"+count);
return (nums.length-count);
}
}
数组中移除特定元素
本文介绍了一种在不使用额外数组的情况下从数组中移除指定值的方法,并保持内存使用为常数。通过双指针技术实现原地删除,同时讨论了元素顺序变化的情况及特殊情况处理。
455

被折叠的 条评论
为什么被折叠?



