1. 程式人生 > 其它 >【JavaSE】---多執行緒

【JavaSE】---多執行緒

題目:https://leetcode-cn.com/problems/move-zeroes/

我的想法:使用一個慢指標和一個快指標,慢指標則是用來尋找陣列中“0”的位置,快指標用來遍歷整個陣列以找到不為“0”的元素,然後互動

程式碼:

C++版本:
void moveZeroes(vector<int>& nums) {
    int fastIndex = 0, slowIndex = 0;
    while ( fastIndex < nums.size()){
        if (nums[slowIndex] == 0 && nums[fastIndex] != 0
){ nums[slowIndex] = nums[fastIndex]; nums[fastIndex] = 0; slowIndex++; } else if (nums[slowIndex] != 0){ slowIndex++; } fastIndex++; } }
JAVA版本:    
public void moveZeroes(int[] nums) {
    int fastIndex = 0, slowIndex = 0;
    
while ( fastIndex < nums.length){ if (nums[slowIndex] == 0 && nums[fastIndex] != 0){ nums[slowIndex] = nums[fastIndex]; nums[fastIndex] = 0; slowIndex++; } else if (nums[slowIndex] != 0){ slowIndex
++; } fastIndex++; } }