775. Global and Local Inversions**
https://leetcode.com/problems/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:
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.
C++ 实现 1
这道题只需要判断 local inversions 和 global inversions 是否完全相等, 那么就需要考虑 “完全相等” 的条件到底是什么. 首先, 对数组进行排序, 比如 [0, 1, 2, 3, 4], 如果一个序列完全有序, local inversions 和 global inversions 均为 0. 要出现 local inversions 和 global inversions 完全相等的情况, 只能是两个相邻的数进行了交换才行, 比如 0 和 1 交换, 数组变成了 [1, 0, 2, 3, 4]. 如果 0 和 2 交换, 数组变成 [2, 1, 0, 3, 4], 此时 local inversion 为 1, global inversions 为 2.
假设排序后的数组为 B,当访问到 A[i], 如果 A[i] != B[i], 那么判断是否 A[i+ 1] == B[i] && A[i] == B[i + 1] 成立.
class Solution {
public:
bool isIdealPermutation(vector<int>& A) {
auto B = A;
std::sort(B.begin(), B.end());
for (int i = 0; i < A.size() - 1; ++ i) {
if (A[i] != B[i]) {
if (A[i + 1] == B[i] && B[i + 1] == A[i])
++ i;
else
return false;
}
}
return true;
}
};
C++ 实现 2
由于 A 是 [0, ..., N - 1] 的组合, 因此一次访问 [0, ... N - 1] 相当于访问排序后的数组 B 了, 就不用像 C++ 实现 1 那样申请额外的空间.
class Solution {
public:
bool isIdealPermutation(vector<int>& A) {
int n = A.size();
for (int i = 0; i < n - 1; i++) {
if (A[i] != i) {
if (A[i+1] != i || A[i] != i+1) return false;
i++;
}
}
return true;
}
};
本文探讨LeetCode上编号为775的问题——全局与局部倒置,提供两种C++实现方案,包括通过排序比较和直接遍历数组的方法,来判断全局倒置与局部倒置数量是否相等。

4452

被折叠的 条评论
为什么被折叠?



