返回信息流给一个数组 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);
}
}
}
// }
};
这是一条镜像帖。来源:北邮人论坛 / cpp / #94493同步于 2017/2/19
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
【问题】请教各位一个数组移动0的小问题
yizisad
2017/2/19镜像同步5 回复
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
秀一下Python:
def move_zeroses(nums):
nums[:] = [x for x in nums if x != 0] + [x for x in nums if x == 0]
【 在 Mrsuyi 的大作中提到: 】
: 你这个解法会把[0, 0, 1]变成[0, 1, 0]
: 原因是你erase+push_back之后直接++i了,忽略了补上来的元素
一语中的,多谢
【 在 nuanyangyang 的大作中提到: 】
: 秀一下Python:
: [code=python]
: def move_zeroses(nums):
: ...................
谢暖神分享