Move Zeroes (E)
題目
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.
Example:
Input: [0,1,0,3,12]
Output: [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.
題意
將陣列中所有0放到最后,其余數按照原有順序放到前面,
思路
見代碼,
代碼實作
Java
class Solution {
public void moveZeroes(int[] nums) {
int p = 0, q = 0;
while (q != nums.length) {
if (nums[q] != 0) {
int tmp = nums[p];
nums[p++] = nums[q];
nums[q] = tmp;
}
q++;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/41150.html
標籤:其他
上一篇:0025. Reverse Nodes in k-Group (H)
下一篇:【學習筆記】計算理論
