283. Move Zeroes

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

 

Follow up: Could you minimize the total number of operations done?


SOL:

參考李根逸博士的影片,loop整個nums,若遇到非零的元素則存回nums(從index 0開始存),因為非零的個數一定少於整個nums,所以可以使用in-place的方式,把非零者直接存回nums

【C 語言的 LeetCode 30 天挑戰】第四天 (Move Zeroes)

文章標籤
全站熱搜
創作者介紹
創作者 yoruru 的頭像
yoruru

yoruru的努力日記

yoruru 發表在 痞客邦 留言(0) 人氣(7)