Global and Local Inversions LT775

We have some permutation A of [0, 1, ..., N - 1], where N is the length of A.

The number of (global) inversions is the number of i < j with 0 <= i < j < N and A[i] > A[j].

The number of local inversions is the number of i with 0 <= i < N and A[i] > A[i+1].

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

Example 1:

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

Example 2:

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

Note:

  • A will be a permutation of [0, 1, ..., A.length - 1].
  • A will have length in range [1, 5000].
  • The time limit for this problem has been reduced.

Idea 1. Local inversion is also global inversion, if the number of global inversions is equal to the number of local inversions, all global inversions are local inversions, which indicates that we only have A[i] > A[i+1], in other words, A[i] > A[j] (j-i <= 1), it's not possible A[i] > A[j] for i <= j-2, max(A[i]) < A[i+2], hence use preMax to store the max value at least 2 slots away and compare it with current value while looping the array.

Time complexity: O(n)

Space complexity: O(1)

 1 class Solution {
 2     public boolean isIdealPermutation(int[] A) {
 3         int preMax = -1;
 4         for(int i = 2; i < A.length; ++i) {
 5             preMax = Math.max(preMax, A[i-2]);
 6             if(preMax > A[i]) {
 7                 return false;
 8             }
 9         }
10         
11         return true;
12     }
13 }

Idea 1.b Adding the information that the array is permutation [0...N-1], cosidering sorted permuation [0, 1, 2,..N-1], to make it have local inversions only, A[i] = ican only swap with it's neighours i+1 or i-1, Math.abs(A[i] -i) <= 1, if Math.abs(A[i] - i) >= 2, it means A[i] either swap with something in the range[0... i-2] or something in the range[i+2...N-1], then there would create global inversion, A[i] > A[j] for i <= j-2.

Time complexity: O(n)

Space complexity: O(1)

 1 class Solution {
 2     public boolean isIdealPermutation(int[] A) {
 3         for(int i = 0; i < A.length; ++i) {
 4             if(Math.abs(A[i] -i) >= 2) {
 5                 return false;
 6             }
 7         }
 8         
 9         return true;
10     }
11 }

猜你喜欢

转载自www.cnblogs.com/taste-it-own-it-love-it/p/10828539.html