[LeetCode] 775. Global and Local Inversions

You are given an integer array nums of length n which represents a permutation of all the integers in the range [0, n - 1].

The number of global inversions is the number of the different pairs (i, j) where:

  • 0 <= i < j < n
  • nums[i] > nums[j]

The number of local inversions is the number of indices i where:

  • 0 <= i < n - 1
  • nums[i] > nums[i + 1]

Return true if the number of global inversions is equal to the number of local inversions. 

Example 1:

Input: nums = [1,0,2]
Output: true
Explanation: There is 1 global inversion and 1 local inversion.

Example 2:

Input: nums = [1,2,0]
Output: false
Explanation: There are 2 global inversions and 1 local inversion.

Constraints:

  • n == nums.length
  • 1 <= n <= 105
  • 0 <= nums[i] < n
  • All the integers of nums are unique.
  • nums is a permutation of all the numbers in the range [0, n - 1].

全局倒置与局部倒置。

给你一个长度为 n 的整数数组 nums ,表示由范围 [0, n - 1] 内所有整数组成的一个排列。

全局倒置 的数目等于满足下述条件不同下标对 (i, j) 的数目:

0 <= i < j < n
nums[i] > nums[j]
局部倒置 的数目等于满足下述条件的下标 i 的数目:

0 <= i < n - 1
nums[i] > nums[i + 1]
当数组 nums 中 全局倒置 的数量等于 局部倒置 的数量时,返回 true ;否则,返回 false 。

来源:力扣(LeetCode)
链接:https://leetcode.cn/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 }

 

LeetCode 题目总结

posted @ 2021-04-05 23:13  CNoodle  阅读(117)  评论(0)    收藏  举报