[LeetCode] 775. Global and Local Inversions
作者:互联网
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.
全局倒置与局部倒置。
数组 A 是 [0, 1, ..., N - 1] 的一种排列,N 是数组 A 的长度。全局倒置指的是 i,j 满足 0 <= i < j < N 并且 A[i] > A[j] ,局部倒置指的是 i 满足 0 <= i < N 并且 A[i] > A[i+1] 。
当数组 A 中全局倒置的数量等于局部倒置的数量时,返回 true 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/global-and-local-inversions
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道数学题。注意这道题的定义
- 数组A是一个从 0 到 N 的 permutation,所以数组里面最小的数字是0,最大的数字是N
- local inversions 在区间内需要严格满足 A[i] > A[i + 1] - 注意local inversions全是在相邻元素之间
- global inversions 在区间内需要严格满足 i < j && A[i] > A[j] - 所以local inversion一定也是一个global inversion
所以 local inversion 一定是一个 global inversion,但是当发现下标和A[i] 偏离了超过1个单位的时候,就说明发现了一个非局部倒置的全局倒置。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public boolean isIdealPermutation(int[] A) { 3 for (int i = 0; i < A.length; i++) { 4 if (Math.abs(i - A[i]) > 1) { 5 return false; 6 } 7 } 8 return true; 9 } 10 }
标签:775,inversion,global,Global,number,inversions,Inversions,倒置,local 来源: https://www.cnblogs.com/cnoodle/p/14619919.html