
代码:因为只要保证非零元素的相对顺序, 借鉴快排的partition。
//
class Solution {
public:
void moveZeroes(vector& nums) {
int tail = 0; // 表示下一个非0 要放的下标
// 【0, tail-1】 表示非0区域 【tail,i】是0区域
for (int i = 0; i < nums.size(); ++i){
if (nums[i] != 0)
swap(nums[i], nums[tail++]);
}
}
};
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)