题目
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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
问题陈述:
把给定数组中的0全部挪到后边,保持其余数字顺序不变
题目思路:
遍历,把非零元素从前向后赋值给原数组,剩余空位补0。
代码:
class Solution { public: void moveZeroes(vector<int>& nums) { int len = nums.size(); int j = 0;//赋值指针 for (int i = 0; i < len; i++) { if (nums[i] != 0) { nums[j] = nums[i]; j++; } else continue; } for (; j < len; j++) {//将后面剩余的空位用0补齐 nums[j] = 0; } } }; |
结果
原文:大专栏 【LeetCode】283. Move Zeros
原文地址:https://www.cnblogs.com/petewell/p/11601691.html
时间: 2024-10-12 17:32:23