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.
1.分析
全局倒置:满足A[i] > A[j], 0 <= i < j < length;局部倒置:满足A[i] > A[i+1], 0 <= i < length。可以明显看出局部倒置是全局倒置的一种特殊情况,题目判断全局倒置和局部倒置的个数是否相等,即相当于判断数列当中是否存在全局倒置(不是局部倒置),比较容易的求解方法利用二层循环进行求解,但这种方法的时间复杂度过高,参考Grandyang博主的思路,其实如果我们仔细观察的话,就会发现,若某个位置上的值和对应的位置坐标差值超过1,则说明肯定会存在不属于局部倒置的全局倒置。例如:
A[5] = 7, 则数组[0,4]位置上最多容纳[0,7]这8个数中的5个,剩下的其他5和6,必定位于位置5的后面,即存在不属于局部倒置的全局倒置;
A[5] = 3, 则[0, 2]最多占据3个位置,说明位置5的前面必定存在比3大的数,即存在不属于局部倒置的全局倒置。
class Solution {
public:
bool isIdealPermutation(vector<int>& A) {
for (int i = 0; i < A.size(); ++i) {
if (abs(A[i] - i) >= 2) return false;
}
return true;
}
};