【leetcode】Move Zeroes

Move Zeroes

题目:

Given an array nums, write a function to move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

一开始的想法是,遍历数组,遇到0就往后移,一直移动最后一步。代码如下

public class Solution {
    public static void moveZeroes(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0 && i != (nums.length - 1)) {
                for (int j = i; j < nums.length - 1; j++) {
                    int temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
            }
        }
    }
}

但是,发现001这个测试用例不对。

恩,发现问题了,因为第一个数为0,第二个0就没办法移动到最后了。

换一种思路,不遍历找0,而是遍历找非0,遇到非0,且不在第一位,就往前移,直到它前面不是0为止。

public class Solution {
    public static void moveZeroes(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0 && i != 0) {
                for (int j = i; j > 0 && nums[j - 1] == 0; j--) {
                    int temp = nums[j - 1];
                    nums[j - 1] = nums[j];
                    nums[j] = temp;
                }
            }
        }
    }
}

这样就解决了

其他方法

public static void moveZeroes(int[] nums) {
        int i = 0, j = 0;
        for (i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                if (j != i) {
                    nums[j] = nums[i];
                    nums[j] = 0;
                }
                j++;
            }
        }
    }

这种方法i遍历数组,只有当i指向为非0时,且ji不同时,j后移,将j处的数改成i处的数,并使i处的数字为0,ij同步后移,而当i指向为0时,只有i后移,j仍然指向0处。

还有一种更简单的方法

public void moveZeroes(int[] nums) {
    if (nums == null || nums.length == 0) return;        

    int insertPos = 0;
    for (int num: nums) {
        if (num != 0) nums[insertPos++] = num;
    }        

    while (insertPos < nums.length) {
        nums[insertPos++] = 0;
    }
}
时间: 2024-10-20 00:05:21

【leetcode】Move Zeroes的相关文章

【5_283】Move Zeroes

终于碰到一道水题,睡觉去~ Move Zeroes Total Accepted: 37369 Total Submissions: 88383 Difficulty: Easy Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums =

【LeetCode】数组

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [1]Two Sum [4]Median of Two Sorted Arrays [11]Container With Most Water [15]3Sum [16]3Sum Closest [18]4Sum [26]Remove Duplicates from Sorted Array [27]Remove Element [31]Next Permutatio

【LeetCode】双指针 two_pointers(共47题)

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 12.0px Helvetica } [3]Longest Substring Without Repeating Characters [11]Container With Most Water [15]3Sum [16]3Sum Closest [18]4Sum [19]Remove Nth Node From End of List [26]Remove Duplicates from Sorted

【Leetcode】Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. Could you devise a constant space solution? 思路:因为需要遍历整个矩阵,时间复杂度肯定需要O(m * n),对于空间复杂度而言,第一种是可以使用O(m * n),对每个位置的0的情况进行记录,第二种是使用O(m + n),对每行每列是否存在0进行记录,第三种是O(1)

【LeetCode】283. Move Zeros

题目 Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note:Yo

【Leetcode】Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in t

【Leetcode】Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 思路:简单的动态规划题目,设f(m, n)为从(0, 0)到达(m

【LeetCode】Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i

【leetcode】657. Robot Return to Origin

Algorithm [leetcode]657. Robot Return to Origin https://leetcode.com/problems/robot-return-to-origin/ 1)problem There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0,