283. Move Zeroes
smart solution
class Solution {
public void moveZeroes(int[] nums) {
int zeroIndex = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
if (i > zeroIndex) { // so smart, 如果沒有, 小於等於的都會變0
nums[zeroIndex] = nums[i];
nums[i] = 0;
}
zeroIndex++;
}
}
}
}
normal solution
if (nums[i] != 0) { // 如果是這樣的資料, Input: [1,0,0,3,12], swap 完, 1還是同個位置
swap(nums, zeroIndex, i);
zeroIndex++;
}
PreviousLintcode - 1870 · Number of Substrings with All ZeroesNext1513. Number of Substrings With Only 1s
Last updated
Was this helpful?