ITPub博客

首页 > IT职业 > IT图书 > Lintcode539 Move Zeroes solution 题解

Lintcode539 Move Zeroes solution 题解

IT图书 作者:gamebus 时间:2021-09-09 09:42:22 0 删除 编辑

【题目描述】

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.

 Notice

You must do this in-place without making a copy of the array.

Minimize the total number of operations.

给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序

 注意事项

1.必须在原数组上操作

2.最小化操作数

【题目链接】

www.lintcode.com/en/problem/move-zeroes/

【题目解析】

1、使用两个"指针"x和y,初始令y = 0

2、利用x遍历数组nums:

3、若nums[x]非0,则交换nums[x]与nums[y],并令y+1

注意:

y指针指向首个0元素可能存在的位置

遍历过程中,算法确保[y, x)范围内的元素均为0

【参考答案】

www.jiuzhang.com/solutions/move-zeroes/



来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4687/viewspace-2806301/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-07-10

  • 博文量
    155
  • 访问量
    13186