BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #94493同步于 2017/2/19
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

【问题】请教各位一个数组移动0的小问题

yizisad
2017/2/19镜像同步5 回复
给一个数组 nums 写一个函数将 0 移动到数组的最后面,非零元素保持原数组的顺序。 我用了两种方法,提交后传入数据[-1,2,-3,4,0,1,0,-2,0,0,1]都没通过。 传别的数据却可以。 各位大佬求指点迷津啊。 class Solution { public: /** * @param nums an integer array * @return nothing, do this in-place */ void moveZeroes(vector<int>& nums) { // Write your code here for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) continue; else { // for (int j = i; j < nums.size(); j++) { // int temp = nums[j+1]; // nums[j+1] = nums[j]; // nums[j] = temp; nums.erase(nums.begin()+i); nums.push_back(0); } } } // } };
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
Mrsuyi机器人#1 · 2017/2/19
你这个解法会把[0, 0, 1]变成[0, 1, 0] 原因是你erase+push_back之后直接++i了,忽略了补上来的元素
nuanyangyang机器人#2 · 2017/2/19
秀一下Python: def move_zeroses(nums): nums[:] = [x for x in nums if x != 0] + [x for x in nums if x == 0]
yizisad机器人#3 · 2017/2/19
【 在 Mrsuyi 的大作中提到: 】 : 你这个解法会把[0, 0, 1]变成[0, 1, 0] : 原因是你erase+push_back之后直接++i了,忽略了补上来的元素 一语中的,多谢
yizisad机器人#4 · 2017/2/19
【 在 nuanyangyang 的大作中提到: 】 : 秀一下Python: : [code=python] : def move_zeroses(nums): : ................... 谢暖神分享
e97ace机器人#5 · 2017/2/19
可以参考下C++自带的std::remove的写法. ———— 主要写JavaScript. 关注广泛, 欢迎交流. 此签名通过「北邮人签名档」脚本发送