Lc286_移动零

package com.example.demo; /** * 283. 移动零 * 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。 * <p> * 示例: * <p> * 输入: [0,1,0,3,12] * 输出: [1,3,12,0,0] * 说明: * <p> * 必须在原数组上操作,不能拷贝额外的数组。 * 尽量减少操作次数。 */ public class Lc283 { //快排的思想 public static void moveZeroes(int[] nums) { int j = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) { if (i > j) { nums[j] = nums[i]; nums[i] = 0; } j++; } } // return; } public static void main(String[] args) { int[] nums = {0, 1, 0, 3, 12}; moveZeroes(nums); for (int i = 0; i < nums.length; i++) { System.out.println(nums[i]); } } }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章