为了保证在不需要Leetcode的情况下也可以运行,我写了测试用例,希望在线下也可以用:

283. Move Zeroes



Total Accepted: 44440 Total Submissions: 103965 Difficulty: Easy

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 MoveZeroes {
	public static void main(String args[]){
		int[] nums= {0, 1, 0, 3, 12};

		int[] OutNum = moveZeroes(nums);
		for(int i=0; i<OutNum.length;i++){
			System.out.println("OutNum="+OutNum[i]);
		}
	}
	public static int[] moveZeroes(int[] nums) {
		int ZeroNum=0;
		for(int i = 0; i <nums.length ;i++){
			if(nums[i]==0){
				ZeroNum++;
			}else{
				nums[i-ZeroNum]=nums[i];
			}
			
		}
		for(int i = nums.length-ZeroNum; i <nums.length ;i++){
				nums[i]=0;
		}
		
		return nums;
    }

}
在leetcode中上传时,注意,最后一句是不需要的。

		return nums;
亏我还以为多复杂,想讲数组转换为列表,这样的结果可能会更好!