283.Move Zeroes == ###### tags: `Leetcode` `python` `c` ### Description (easy) Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. #### example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] #### example 2: Input: nums = [0] Output: [0] #### Constraints: - 1 <= nums.length <= 104 - -231 <= nums[i] <= 231 - 1 ### 想法 看到問題蠻直觀就想到解法,一開始先用while 跑一次nums[],不使用for loop 怕等等用pop會整個List亂掉,然後用count記錄下pop掉幾的0,最後在再append到List的最尾端。 ### 程式碼 #### python: ```python= class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ index = 0 count = 0 while index<len(nums): if nums[index]==0: nums.pop(index) count+=1 else: index+=1 for j in range(count): nums.append(0) ``` Runtime: 170 ms Memory Usage: 15.6 MB #### c: ```c= void moveZeroes(int* nums, int numsSize){ int *ans=calloc(numsSize, sizeof(int)); int top=0; for(int i=0; i<numsSize; i++){ if(nums[i]!=0){ ans[top]=nums[i]; top++; } } for(int i=0; i<numsSize; i++){ nums[i]=ans[i]; } } ``` Runtime: 131 ms Memory Usage: 15.4 MB Your runtime beats 55.10 % of c submissions.