Python O(n) 3 lines solution

  • 0

    The idea is simple, if i is odd, means nums[i-1] < nums[i] should NOT satisfy. If i is even, nums[i-1] < nums[i] should satisfy. So we can use ^ to combine the two conditions.

        for i in range(1, len(nums)):
            if (nums[i-1] < nums[i]) ^ ((i&1) == 1):
                nums[i-1:i+1] = [nums[i], nums[i - 1]]

  • 0

    not seems right, try [1,1,1,1,2,2,2,2]

Log in to reply

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