簡體   English   中英

Java If/While循環比較

[英]Java Comparison of If/While Loop

處理一個 leetcode 問題,描述為:“給定一個二進制數組 nums 和一個 integer k,如果最多可以翻轉 k 個 0,則返回數組中連續 1 的最大數量。”

我正在使用滑動 window 方法並生成了以下代碼:

class Solution {
    public int longestOnes(int[] nums, int k) {
        int current = 0;
        int left = 0;
        int ans = 0;
           
        for (int right = 0; right < nums.length; right++){
            if (nums[right] == 0){
                current++;
            }         
            
            while (current > k){
                if (nums[left] == 0){
                    current--;
                }
                left++;
            }

            ans = right - left + 1;    
        }
        return ans;
    }
}

這會在輸出中產生一個邏輯錯誤,其中返回的值根據測試在任一方向上相差 1。 我用下面代碼中顯示的if語句替換了while循環,該語句修復了錯誤。 為什么會這樣?

class Solution {
    public int longestOnes(int[] nums, int k) {
        int current = 0;
        int left = 0;
        int ans = 0;
           
        for (int right = 0; right < nums.length; right++){
            if (nums[right] == 0){
                current++;
            }         
            
            if (current > k){
                if (nums[left] == 0){
                    current--;
                }
                left++;
            }
            ans = right - left + 1;    
        }
            
        return ans;
    }
}

我希望while循環運行一次並且等效於該塊應該在每次迭代時評估條件,然后在條件為真時采取行動。 這里發生了什么?

解決方案移@SiggyWeb的問題帖子:

通過評論反饋找到的解決方案

class Solution { public int longestOnes(int[] nums, int k) { int current = 0; int left = 0; int ans = 0; for (int right = 0; right < nums.length; right++){ if (nums[right] == 0){ current++; } while (current > k){ if (nums[left] == 0){ current--; } left++; } ans = Math.max(ans,right - left + 1); } return ans; } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM