LeetCode之Move Zeroes

122 阅读2分钟

1、题目

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:

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

2、代码实现

这个代码可以AC

public class Solution {
    public void moveZeroes(int[] nums) { 
		if (nums == null || nums.length == 0)
	    	 return;
	     int length = nums.length;
	     int allZero = 0;
	     for (int i = 0; i < length; ++i) {
	    	 if (nums[i] == 0)
	    		 allZero++;
	     }
	     int count = 0;
	     for (int i = 0; i < length; ++i) {
	    	 if (nums[i] != 0) {
	    		 nums[count++] = nums[i];
	    		 if (count == length - allZero) 
	    			 break;
	    	 }
	     }
	     for (int i = count; i < length; ++i)
	    	 nums[count++] = 0;
	    	
	}
}

 

下面的代码是我通过思路,通过遍历所有的数字,想遇到一个0,然后数据左移,如果数据不是0,不动, 特么发现还是蛮复杂的,而且只测试了部分可以,但是不能过AC,比如

{0, 0 ,1},像日了狗一样

	public static void moveZeroes1(int[] nums) {
	     if (nums == null || nums.length == 0)
	    	 return;
	     int length = nums.length;
	     int count = 0;
	     for (int i = 0; i < length - 1; ++i) {
	    	 if (nums[i] == 0) {
	    		 for (int j = i ; j <= length - i; j++) {
	    			 if (j + 1 < length) {
	    				 nums[j] = nums[j + 1];
	    			 }
	    		 }
	    		 nums[length - 1] = 0;
	    	 }
	     }
	}



 

3、思考和总结

思路一、

通过遍历所有的数字,想遇到一个0,然后数据左移,如果数据不是0,不动, 特么发现还是蛮复杂的,而且只测试了部分可以,但是不能过AC,比如

{0, 0 ,1},像日了狗一样,而且搞了很久,没搞出来,心都快奔溃了,

 

思路二、

如果一个题目搞了很久没搞出来,那么我们应该换思路思考这个问题,就像做项目产品一样,如果感觉越做越复杂,越做越不清楚,估计架构就有问题,果断放弃,因该是觉得越做越简单,很明显呀,一位数组,我们大不了从来组装数组,把不等于0的数据依依放在从下表为0的开始的位置,然后进行index++,然后算出0的个数,得到不为0的个数,当所有我们填充的数据慢慢增加到不为0的个数的时候,我们break,然后再把后面所有的数据赋值为0就可以了,以后要形成条件反射,看到一位数组需要改变顺序的,我们第一个想到的应该是,从下标0开始赋值,然下标慢慢变大,再赋我们需要的数据,而不是傻不拉几的去移动数组,而且有时候还不需要移动数组,增加题目的复杂度。

 

 

创作打卡挑战赛

赢取流量/现金/CSDN周边激励大奖