Leetcode学习笔记:#283. Move Zeroes

该博客是Leetcode #283. Move Zeroes的学习笔记。题目要求将数组中所有0移到末尾,同时保持非零元素相对顺序。实现思路是用insertPos记录非0数字个数,遍历数组将非0数字排前,再根据insertPos与数组长度差值确定0的个数。

Leetcode学习笔记:#283. Move Zeroes

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.

实现:

public void moveZeroes(int[] nums){
	if(nums == null || nums.length == 0)
		return;

	int insertPos = 0;
	for(int num : nums){
		if(num != 0) nums[insertPos++] = num;
	}
	while(insertPose < nums.length){
		nums[insertPos++]=0;
	}
}

思路:
用一个insertPos来记录非0的数字有多少个,遍历整个数组,把非0数字排在前面,再把Insertpos与数组长度比较,少于数组长度的则是0的个数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值