Move Zeroes

来源:互联网 发布:美国bt下载软件 编辑:程序博客网 时间:2024/06/03 15:45

 

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.
public class Solution {    public void moveZeroes(int[] nums) {        if(nums == null || nums.length == 0) return;        int pre = 0; int cur = 0;        while(cur<nums.length){            if(nums[cur]!=0){                nums[pre++] = nums[cur];            }            cur++;           }        while(pre<nums.length){            nums[pre++] = 0;        }    }}
方法2:利用互换;

public class Solution {    public void moveZeroes(int[] nums) {        if(nums == null || nums.length == 0) return;        int i =0; int j=i+1;        while(j<nums.length){            if(nums[i] == 0){                if(nums[j] != 0){                    swap(nums, i, j);                    i++;                    j++;                } else {                    j++;                }            } else {                i++;                j++;            }        }    }        public void swap(int[] nums, int i, int j){        int temp = nums[i];        nums[i] = nums[j];        nums[j] = temp;    }}



0 0
原创粉丝点击