775. Global and Local Inversions
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了775. Global and Local Inversions相关的知识,希望对你有一定的参考价值。
We have some permutation
A
of[0, 1, ..., N - 1]
, whereN
is the length ofA
.The number of (global) inversions is the number of
i < j
with0 <= i < j < N
andA[i] > A[j]
.The number of local inversions is the number of
i
with0 <= i < N
andA[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.
Approach #1: Array. [Java]
class Solution { public boolean isIdealPermutation(int[] A) { int n = A.length; for (int i = 0; i < n; ++i) { if(Math.abs(A[i] - i) > 1) return false; } return true; } }
Analysis:
The origainal order should be [0, 1, 2, 3, 4....], the number i should be on the position i. We just check the offset of each number, if the absolute value is large than 1, means the number of global inverion must be bigger than local inversion, because a local inversion is a global inversion, but a global one may not be local.
Proof:
If A[i] > i + 1, means at least one number that is smaller than A[i] is kicked out from first A[i] numbers, and the distance between this smaller number and A[i] is at least 2, then it is a non-local global inversion.
For example, A[i] = 3, i = 1, at least one number that is smaller than 3 is kicked out from first 3 numbers, and the distance between the smaller number and 3 is at least 2.
If A[i] < i - 1, means at least one number that is bigger than A[i] is kicked out from last n-i numbers, and the distance between this bigger number and A[i] is at least 2, then it is a non-local global inversion.
Reference:
https://leetcode.com/problems/global-and-local-inversions/discuss/113656/My-3-lines-C%2B%2B-Solution
以上是关于775. Global and Local Inversions的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 775. Global and Local Inversions ---找规律
[leetcode-775-Global and Local Inversions]
[LeetCode] Global and Local Inversions 全局与局部的倒置
翻译自mos文章关于分区索引:Global, Local, Prefixed and Non-Prefixed