LeetCode 0775. Global and Local Inversions Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
0775. Global and Local Inversions

Description

You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].

The number of global inversions is the number of the different pairs (i, j) where:

  • 0 <= i < j < n
  • nums[i] > nums[j]

The number of local inversions is the number of indices i where:

  • 0 <= i < n - 1
  • nums[i] > nums[i + 1]

Return true if the number of global inversions is equal to the number of local inversions.

 

Example 1:

Input: nums = [1,0,2]
Output: true
Explanation: There is 1 global inversion and 1 local inversion.

Example 2:

Input: nums = [1,2,0]
Output: false
Explanation: There are 2 global inversions and 1 local inversion.

 

Constraints:

  • n == nums.length
  • 1 <= n <= 105
  • 0 <= nums[i] < n
  • All the integers of nums are unique.
  • nums is a permutation of all the numbers in the range [0, n - 1].

Solutions

Solution 1

PythonJavaC++Go
class Solution: def isIdealPermutation(self, nums: List[int]) -> bool: mx = 0 for i in range(2, len(nums)): if (mx := max(mx, nums[i - 2])) > nums[i]: return False return True(code-box)

Solution 2

PythonJavaC++Go
class BinaryIndexedTree: def __init__(self, n): self.n = n self.c = [0] * (n + 1) def update(self, x, delta): while x <= self.n: self.c[x] += delta x += x & -x def query(self, x): s = 0 while x: s += self.c[x] x -= x & -x return s class Solution: def isIdealPermutation(self, nums: List[int]) -> bool: n = len(nums) tree = BinaryIndexedTree(n) cnt = 0 for i, v in enumerate(nums): cnt += i < n - 1 and v > nums[i + 1] cnt -= i - tree.query(v) if cnt < 0: return False tree.update(v + 1, 1) return True(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !