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:
-
Awill be a permutation of[0, 1, ..., A.length - 1]. -
Awill have length in range[1, 5000]. - The time limit for this problem has been reduced.
思路
值的范围是从0~A.length-1,设想一种情况:
风平浪静,一切都好,既没有global,也没能local
| 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 |
如果4放到了位置2,那么无论怎么摆放其他数字,4一定比后面某二个数字大:
| 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| * | * | 4 | * | * |
试想下面这种极端情况:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| * | * | 4 | 5 | 6 | 7 | * | * |
同理,如果把2放到位置3,无论怎么摆放数字,2都比前面的某个数字小:
| 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| * | * | * | 2 | * |
依据这个规律可以进行计算:如果发现|A[i] - i| > 1,说明A[i]的前/后,一定存在多个k,k的值一定大于/小于A[i],那么一定会让global多于local。
java
class Solution {
public boolean isIdealPermutation(int[] A) {
for (int i = 0; i < A.length; i++) {
if (Math.abs(A[i]-i) > 1) return false;
}
return true;
}
}
