LN : leetcode 283 Move Zeroes

时间:2023-03-08 15:08:20
LN : leetcode 283 Move Zeroes

lc 283 Move Zeroes


283 Move Zeroes

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].

analysation##

刚开始用了很蠢的方法,后来用STL很轻松就解决了!

solution1:蠢

void moveZeroes(vector<int> & nums) {
if (nums.size() <= 1) {
return;
} else {
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] != 0) {
nums[sum] = nums[i];
sum++;
}
}
for (int i = sum; i < nums.size(); i++)
nums[i] = 0;
}
}

solution2:STL

int size = nums.size();
int pos = 0;
for (int i = 0; i < size; i++) {
if (nums[i] != 0) {
int temp = nums[i];
nums.erase(nums.begin() + i);
nums.insert(nums.begin() + pos, temp);
pos += 1;
}
}