leetcode 283. Move Zeroes
第一次写的代码,实际效率是O(n)的,但判断多了一点。
void moveZeroes(vector<int>& nums) { int first_zero = 0; int first_num = 1; while (first_zero < first_num && first_num < nums.size()) { while (first_zero < nums.size() && nums[first_zero] != 0) first_zero++; while (first_num < nums.size() && (first_num <= first_zero || nums[first_num] == 0)) first_num++; if (first_num >= nums.size()) break; swap(nums[first_zero], nums[first_num]); first_zero++; first_num++; } }
其实可以很简洁:
void moveZeroes(vector<int>& nums) { int i = 0; int j = 0; while (i < nums.size()) { if (nums[i]) nums[j++] = nums[i]; i++; } while (j < nums.size()) nums[j++] = 0; }
【本文章出自博客园willaty,转载请注明作者出处,误差欢迎指出~】