solution_1:
1 class Solution { 2 public: 3 void moveZeroes(vector<int>& nums) { 4 int k = 0; // k # number of zero element 5 for(int i = 0; i < nums.size(); i++){ 6 if(nums[i] != 0){ 7 nums[k++] = nums[i]; 8 } 9 } 10 for(; k < nums.size(); k++){ 11 nums[k] = 0; 12 } 13 } 14 };
solution_2:
1 class Solution { 2 public: 3 void moveZeroes(vector<int>& nums) { 4 int k = 0; 5 for(int i = 0; i < nums.size(); i++){ 6 if(nums[i] != 0){ 7 swap(nums[k++], nums[i]); 8 } 9 } 10 11 } 12 };
solution_3:
1 class Solution { 2 public: 3 void moveZeroes(vector<int>& nums) { 4 vector<int> nonZeros; 5 for(int i = 0; i < nums.size(); i++){ 6 if (nums[i]) 7 nonZeros.push_back(nums[i]); 8 } 9 for(int i = 0; i < nonZeros.size(); i++){ 10 nums[i] = nonZeros[i]; 11 } 12 for(int i = nonZeros.size(); i < nums.size(); i++){ 13 nums[i] = 0; 14 } 15 } 16 };
solution3 看似最蠢,其实是最快的