java Leetcode移动零:我的bug在哪里?
这是一个简单的问题a link 我只是尝试了简单的insertionSorting方法来解决它,但是失败了
public class Solution {
public void moveZeroes(int[] nums) {
for(int i = 0; i < nums.length; i++)
if(nums[i] == 0){
for(int j = i; j<nums.length-1; j++)
nums[j] = nums[j+1];
nums[nums.length-1] = 0;
}
}
}
有人能帮我调试我的方法吗
# 1 楼答案
我将分享leetcode中针对移动零点问题的javascript解决方案。它具有O(n)时间复杂度
针对多个零进行了优化
针对更少的零进行了优化
示例
# 2 楼答案
请在下面的空间O(N)和时间O(1)中找到最优解
# 3 楼答案
所以我检查了你的代码并重新编写了它。如果你把零移到最后,这对你来说应该很好。干杯
这段代码的作用是在数组上迭代,直到它达到零。当碰到一个0时,它会循环,将0一个位置反复向右移动,用它右边的值切换点,直到0移动到数组的末尾
示例:5回路循环 [0,1,0,2,3]>;[1,0,0,2,3]>;[1,0,0,2,3]>;[1,0,2,0,3]>;[1,0,2,3,0]
# 4 楼答案
我将尝试写一个非常直观和简单的方法来解决这个问题。这个问题可以通过使用两个索引来解决,一个是读指针(rp),另一个是写指针(wp)
如果rp读取的值为0,则将wp设置为此索引。然后rp继续递增,直到找到非零值。如果它这样做,它将覆盖wp处的值,并且此过程将在开始时填充非零值
然后我们只需要用零填充剩余的点,直到结束。下面是python中的一个简短解决方案: