Leetcode-Move Zeroes

来源:互联网 发布:淘宝不能复制宝贝 编辑:程序博客网 时间:2024/06/03 20:08

每天再忙还是要坚持刷题的,虽然只刷1-2道题,但是坚持下去就会有效果!【我真的不是在用心灵鸡汤在为自己刷的少找借口吗?】


Question:

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.

Solution:
1、比较笨的办法,就是借用冒泡排序法的思想,将0和非0得位置进行交换,使得前面的数字全部是0

代码如下:
  public class Solution {
    public void moveZeroes(int[] nums) {
        int numslength = nums.length;
        // 用于交换
        int flag;
        for(int i=0;i<numslength;i++){
          if(nums[i]==0){
             for(int j=i;j<numslength;j++){
               if(nums[j]!=0){
                  flag = nums[i];
                  nums[i]=nums[j];
                  nums[j] =flag;
                   break;
               }  
             }
          }
        }
    }
}

2、注意到0的特殊性和一致性。可以把非零部分全部压缩到前面,然后后面只管填零。
代码如下:
 public class Solution {
    public void moveZeroes(int[] nums) {
   int  after = 0;
for(int i=0; i < nums.length; i++){
if(num[i] != 0){
    nums[after] = nums[i];
    after ++;
}
}
//将剩余置为0
for(;after < nums.length; after++){
     nums[after] = 0;
}
}
}

0 0
原创粉丝点击