775. Global and Local Inversions

2018/10/05 leetcode 共 782 字,约 3 分钟

title

problem link

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.

solution

求逆序对数和a[i]>a[i+1]数量是否相等,可判断max(a[0:i-2])是否有大于a[i]即可

class Solution {
public:
	bool isIdealPermutation(vector<int>& A) {
		if (A.size() <= 2) return true;
		int t = A[0];
		for (int i = 2; i < A.size(); i++) {
			t = max(t, A[i - 2]);
			if (t > A[i]) {
				return false;
			}
		}
		return true;

	}
};

Search

    Table of Contents