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] .
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
這題和 Remove Element 類似
但不同的點在於,必須保持原本的順序
解題想法如下
- 先將所有非零的數,一個一個從前面按順序排好
- 剩餘的位置,全部都填 0
Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public void moveZeroes(int[] nums) { | |
int index = 0; | |
for(final int n : nums) { | |
if(n != 0) { | |
nums[index++] = n; | |
} | |
} | |
while(index < nums.length) { | |
nums[index++] = 0; | |
} | |
} | |
} |
或者直接swap 也是可以
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun moveZeroes(nums: IntArray): Unit { | |
var index = 0 | |
for(i in nums.indices) { | |
if(nums[i] != 0) { | |
nums[index] = nums[i].also { nums[i] = nums[index] } | |
++index | |
} | |
} | |
} | |
} |
沒有留言:
張貼留言