2017年11月27日 星期一

[LeetCode] 283. Move Zeroes

轉自LeetCode

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:
  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
<Solution>
這題和 Remove Element 類似

但不同的點在於,必須保持原本的順序

解題想法如下
  • 先將所有非零的數,一個一個從前面按順序排好
  • 剩餘的位置,全部都填 0
code 如下

Java
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;
}
}
}
view raw moveZeros.java hosted with ❤ by GitHub

或者直接swap 也是可以

kotlin
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
}
}
}
}
view raw move_zeroes.kt hosted with ❤ by GitHub

沒有留言:

張貼留言