【LeetCode】Move Zeroes

来源:互联网 发布:网络另类说唱歌手 编辑:程序博客网 时间:2024/06/10 15:09
Move Zeroes
My Submissions Question Solution 
Total Accepted: 9333 Total Submissions: 21879 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 = [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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
【解题思路】
按顺序移位赋值,后面的就全部是0。

Java AC

public class Solution {    public void moveZeroes(int[] nums) {        int len = nums.length;        int i = 0;        int j = 0;        while(j < len){            if(nums[j] != 0){                nums[i++] = nums[j];            }            j++;        }        while(i < len){            nums[i] = 0;            i++;        }    }}


0 0