这道题没什么好说的,不过我没有一遍直接通过测试。因为有一个逻辑漏洞没有在边缘的地方进行判断,这里就针对这一点说一下吧。
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:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
我的代码
public class Solution {
public void moveZeroes(int[] nums) {
int zeroNum=0;
for(int i=0;i<nums.length;i++){
if (nums[i]==0){
zeroNum++;
continue;
}
else{
nums[i-zeroNum]=nums[i];
if((i-zeroNum)!=i){//第一个版本没有这个判断
nums[i]=0;
}
}
}
return ;
}
}
从容的算法
一个好的算法应该是有一种面对边界或者特殊情况如同面对一般情况一样从容的感觉。
对于没有意义同时也解决不了的边界情况的排除。对于构不成主要逻辑的边界,但是存在意义的判断和补充。这些让一个算法显得从容一些。
我的解法中一开始没有考虑那种输入只有一个数字的情况。而那个出错语句是为了不用第二次从结尾处进行遍历吧0补全的小聪明。
当你要刷一个小聪明的时候,你就要从全局检查一遍,看看这个聪明是否被全局所包容。