LeetCode之Move Zeroes
发布日期:2021-06-29 14:08:10 浏览次数:2 分类:技术文章

本文共 1825 字,大约阅读时间需要 6 分钟。

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开始赋值,然下标慢慢变大,再赋我们需要的数据,而不是傻不拉几的去移动数组,而且有时候还不需要移动数组,增加题目的复杂度。
 

 

转载地址:https://chenyu.blog.csdn.net/article/details/68639063 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode之Excel Sheet Column Number
下一篇:LeetCode之Intersection of Two Arrays

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年05月02日 05时48分22秒