/* * 283. Move Zeroes * 12.7 by Mingyang * 不用什么两个指针不指针的问题啦,一个一个慢慢来 需要把0换到后面去 */ public static void moveZeroes(int[] nums) { if (nums.length == 0 || nums == null) return; int start = -1; for (int i = 0; i < nums.length; i++) { // 找到第一个不是0的值,并且赋予start这个index if (nums[i] == 0 && start < 0) { start = i; } if (nums[i] != 0 && start >= 0) { swap(nums, i, start); i = start; start = -1; } } } public static void swap(int A[], int i, int j) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } // 哪里用什么换哦,没那么复杂啦,直接所有的前面全部填满,后面全部补0,不是换 public void moveZeroes1(int[] nums) { int len=nums.length; int index=0; for(int i=0;i<len;i++){ if(nums[i]!=0){ nums[index]=nums[i]; index++; } } for(int i=index;i<len;i++){ nums[i]=0; } } // 我喜欢的思路,直接!两个指针 public static void moveZeroes2(int[] nums) { if (nums.length <= 1) return; int first = 0; int sec = 0; while (sec < nums.length) { // find first zero element while (first < nums.length && nums[first] != 0) { first++; } if (first == nums.length) return; sec = first + 1; // find following first non-zero element while (sec < nums.length && nums[sec] == 0) { sec++; } if (sec == nums.length) return; swap(nums, first, sec); } }