有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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;
            }
    }
}

有人能帮我调试我的方法吗


共 (4) 个答案

  1. # 1 楼答案

    我将分享leetcode中针对移动零点问题的javascript解决方案。它具有O(n)时间复杂度

    针对多个零进行了优化

    const snowball1 = nums => {
      let i = 0;
      let j = 0;
      while (i<nums.length) {
        if(nums[i] != 0) {
          nums[j] = nums[i];
          j++;
        }
        i++;
      }
      console.log(j);
      nums.fill(0, j);
      return nums;
    }
    

    针对更少的零进行了优化

    const snowball2 = nums => {
      for(let i = nums.length; i--;){
        if(nums[i]===0){
          nums.splice(i,1)
          nums.push(0);
        }
      }
      return nums
    }
    

    示例

    console.log(snowball1([0,0,1,0,0,3,0,12,0]));
    console.log(snowball2([0,1,0,3,12]));
    
  2. # 2 楼答案

    请在下面的空间O(N)和时间O(1)中找到最优解

    public void moveZeroes(int[] nums) {
        // [0,1,0,3,12]
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                j++;
            }
        }
    }
    
  3. # 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]

    int[] array = new int[] {0,1,0,12,3};
    
    for (int x = 0; x < array.length; x++) {
        if (array[x] == 0) {
            for (int y = x; y < array.length; y++) {
                if (y  != array.length-1) {
    
                    // Store our replacement as temp
                    int temp = array[y+1];
    
                    // Move 0 to the right +1
                    array[y+1] = array[y];
    
                    // Set current position to what used to be right+1
                    array[y] = temp;
                }
            }
        }
    }
    
  4. # 4 楼答案

    我将尝试写一个非常直观和简单的方法来解决这个问题。这个问题可以通过使用两个索引来解决,一个是读指针(rp),另一个是写指针(wp)

    如果rp读取的值为0,则将wp设置为此索引。然后rp继续递增,直到找到非零值。如果它这样做,它将覆盖wp处的值,并且此过程将在开始时填充非零值

    然后我们只需要用零填充剩余的点,直到结束。下面是python中的一个简短解决方案:

    class Solution:
        def moveZeroes(self, nums: List[int]) -> None:
            wp=rp=0
            while(rp<len(nums)):
                if(nums[rp]!=0):
                    nums[wp]=nums[rp]
                    wp+=1
                rp+=1
            for i in range(wp,len(nums)):
                nums[i]=0