菜鸟初刷LeetCode——数组(6) moveZeroes移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:

输入: [0,1,0,3,12]
输出: [1,3,12,0,0]

说明:

  1. 必须在原数组上操作,不能拷贝额外的数组。
  2. 尽量减少操作次数。

思路:

遍历,另外在维护一个指向非0数的索引,当当前数字为0,就将这个数字和索引指向的数字交换。

当索引已经在末尾了,则后面已经没有非0数字了,就直接将数字置0就行了

 

/**
 * Created with IntelliJ IDEA.
 * Description:给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
 * 必须在原数组上操作,不能拷贝额外的数组。
 尽量减少操作次数。
 * User: hhj
 * Date: 2018-08-26
 * Time: 8:57
 */
public class MoveZeroes {
    public static void moveZeroes(int[] nums) {
        int index = 0;
        int len = nums.length;
        for (int i=0; i<len-1; i++){
            if (index == len-1){
                nums[i] = 0;
                continue;
            }
            if (nums[i] == 0){
                if (index<i){
                    index = i;
                }
                index++;
                while (index<=len-2 && nums[index] == 0){
                    index++;
                }
                if (nums[index] != 0){
                    nums[i] = nums[index];
                    nums[index] = 0;
                }
            }
        }
        for (int num:nums){
            System.out.println(num);
        }
    }

    public static void main(String[] ars){
        int[] arr = {0,1,0,3,12};
        moveZeroes(arr);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章