原题
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.
题目分析
要求移除指定元素,空间复杂度为O(1)。
代码实现
public int RemoveElement(int[] nums, int val)
{
int i=0; //指向不等于元素val
for(int j=0; j<nums.Length;j++)
{
while(j<nums.Length&&nums[j]==val)
j++;
if(i<j && j<nums.Length)
nums[i]= nums[j];
if(j<nums.Length)
i++;
}
return i;
}
leetcode-solution库
leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

本文提供了一种解决LeetCode上移除指定元素问题的方法,该方法在原数组上操作,确保空间复杂度为O(1),适用于需要高效移除特定值的场景。
266

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



