283. Move Zeroes

来源:互联网 发布:英语有声阅读软件 编辑:程序博客网 时间:2024/06/06 02:36

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

其实可以考虑改一下传统的排序方法进行计算。我是基于冒泡排序进行了改进。


class Solution {    public void moveZeroes(int[] nums) {        int temp;        for (int i = 0; i < nums.length-1; i++){            for(int j = 0; j < nums.length-1-i; j++){                if(nums[j] == 0 && nums[j+1] != 0){                    temp = nums[j];                    nums[j] =nums[j+1];                    nums[j+1] = temp;                }            }        }    }}
原创粉丝点击