[Leetcode]457-環形數組循環(Java)

給定一個含有正整數和負整數的環形數組 nums。 如果某個索引中的數 k 爲正數,則向前移動 k 個索引。相反,如果是負數 (-k),則向後移動 k 個索引。因爲數組是環形的,所以可以假設最後一個元素的下一個元素是第一個元素,而第一個元素的前一個元素是最後一個元素。

確定 nums 中是否存在循環(或週期)。循環必須在相同的索引處開始和結束並且循環長度 > 1。此外,一個循環中的所有運動都必須沿着同一方向進行。換句話說,一個循環中不能同時包括向前的運動和向後的運動。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/circular-array-loop

[Java]比較原始的方法,容易理解,時間複雜度略高

 public boolean circularArrayLoop(int[] nums) {
        boolean flag = false;
        for (int i = 0, length = nums.length; i < length; i++) {
            int preValue = nums[i];//這也是index移動的值
            if (Math.abs(preValue) == length)//判斷移動的值是否爲數組的長度,即避免循環
                continue;
//這個三目運算符的意思是看看最終的index是否爲負,因爲java中被除數如果爲負,那麼餘數也爲負,在數組中需要把正和負單獨拎出來處理,outer的意思僅僅是和while循環裏的做區分
            int outerIndex = (i + preValue) < 0 ? (i + preValue) % length + length : (i + preValue) % length;
            int nowValue = nums[outerIndex];//記錄下一個index的值
            int index = outerIndex;//這個值是要和i進行對比
            int count = 0;//這個值是爲了能夠跳出循環
            //三個條件①跳動的方向要一致②index一致③循環的次數不能超過length
            while (preValue * nowValue > 0 && index != i && count < length) {
                count++;
//迭代式的進行操作,基本上和第一次的處理差不多,可能有一點細節不同
                preValue = nowValue;
                if (Math.abs(preValue) == length)
                    continue;
                int innerIndex = (index + preValue) < 0 ? (index + preValue) % length + length : (index + preValue) % length;
                nowValue = nums[innerIndex];
                if (Math.abs(nowValue) == length)
                    continue;
                index = innerIndex;
                if (index % length == i){
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章