Python single node list solution


  • 0
    class Node(object):
        def __init__(self, val, index):
            self.val = val
            self.index = index
            self.next = None
            
    class Solution(object):
        def canCompleteCircuit(self, gas, cost):
            """
            :type gas: List[int]
            :type cost: List[int]
            :rtype: int
            """
            head = Node(gas[0] - cost[0], 0)
            node = head
            for i, j in enumerate(gas[1:], 1):
                node.next = Node(j - cost[i], i)
                node = node.next
            node.next = head
            index = []
            temp1 = []
            node = head
            start = None
            while node.next != node:
                if start is not None and node.index == start:
                    break
                if node.val >= 0:
                    if start is None:
                        start = node.index
                    temp = node.next
                    while temp != node and node.val >= 0:
                        node.val += temp.val
                        temp = temp.next
                    node.next = temp
                node = node.next
            if node.val >= 0:
                return node.index
            else:
                return -1

Log in to reply
 

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