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].
分析
meh
解决方案1(Python)
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution(object): defmoveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i = 0 for item in nums: if item != 0: nums[i] = item i += 1 for j in range(i, len(nums)): nums[j] = 0
解决方案1(C++)
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: voidmoveZeroes(vector<int>& nums){ int j = 0; for(int i = 0; i < nums.size(); i++){ if(nums[i] != 0){ nums[j++] = nums[i]; } } memset(&nums[j], 0, sizeof(int)*((int)nums.size()-j)); } };