【LeetCode】283. Move Zeroes 解題報告
283. Move Zeroes / 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 <= 10^4
- -2^31 <= nums[i] <= 2^31 - 1
Solution
思路
跟 26. Remove Duplicates from Sorted Array 有點像,用兩個指標,一前一後移動,一遇到 0,就把兩個指標的內容互換。
效能
Complexity
- Time Complexity: O(N)
- Space Complexity: O(1)
LeetCode Result
- Runtime: 36 ms
- Memory Usage: 19.3 MB
- https://leetcode.com/submissions/detail/538798757/
Code
1 | class Solution { |