0
点赞
收藏
分享

微信扫一扫

【Leetcode】Move Zeroes

微笑沉默 2023-07-26 阅读 12


题目链接:https://leetcode.com/problems/move-zeroes/

题目:

nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.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
  2. Minimize the total number of operations.

思路:

记录0的数目n,然后将数组最后n个数置0。实质是删除操作,参见

算法:

public void moveZeroes(int[] nums) {
		int count = 0;
		for (int i = 0; i < nums.length; i++) {
			if (nums[i] == 0) {
				count++;
			} else {
				nums[i - count] = nums[i];
			}
		}
		for (int j = 0; j < count; j++) {
			nums[nums.length - 1 - j] = 0;
		}

	}




举报

相关推荐

0 条评论