ITPub博客

首页 > 应用开发 > IT综合 > Lintcode539 Move Zeroes solution 题解

Lintcode539 Move Zeroes solution 题解

原创 IT综合 作者:chimmychimmy 时间:2018-08-02 22:59:58 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/31548498/viewspace-2169027/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 没有了~
下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2018-08-02

  • 博文量
    1
  • 访问量
    268