Python Solution, O(n) and space O(1) can you guys help to optimize?


  • 0
    X
    class Solution(object):
        def circularArrayLoop(self, nums):
    
            if len(nums) > 2:
                currentIndex = 0
                for i in range(0, len(nums)):
                    if (nums[0] > 0 and nums[currentIndex] < 0) or (nums[0] < 0 and nums[currentIndex] > 0):
                        return False
                    
                    if nums[currentIndex] < 0:
                        if currentIndex == 0:
                            currentIndex = len(nums) - abs(nums[currentIndex])
                        else:
                            currentIndex = currentIndex - abs(nums[currentIndex])
                    
                        if currentIndex < 0:
                            currentIndex = currentIndex + len(nums)
                    elif (currentIndex + nums[currentIndex]) >= len(nums):
                        currentIndex = currentIndex + nums[currentIndex] - len(nums)
                    else:
                        currentIndex += nums[currentIndex]
                
                    if currentIndex == 0:
                        return True
        
            return False

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.