zoukankan      html  css  js  c++  java
  • 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.

    Approach #1: Array. [Java]

    class Solution {
        public boolean isIdealPermutation(int[] A) {
            int n = A.length;
            for (int i = 0; i < n; ++i) {
                if(Math.abs(A[i] - i) > 1) return false;
            }
            return true;
        }
    }
    

      

    Analysis:

    The origainal order should be [0, 1, 2, 3, 4....], the number i should be on the position i. We just check the offset of each number, if the absolute value is large than 1, means the number of global inverion must be bigger than local inversion, because a local inversion is a global inversion, but a global one may not be local.

    Proof:

    If A[i] > i + 1, means at least one number that is smaller than A[i] is kicked out from first A[i] numbers, and the distance between this smaller number and A[i] is at least 2, then it is a non-local global inversion.

    For example, A[i] = 3, i = 1, at least one number that is smaller than 3 is kicked out from first 3 numbers, and the distance between the smaller number and 3 is at least 2.

    If A[i] < i - 1, means at least one number that is bigger than A[i] is kicked out from last n-i numbers, and the distance between this bigger number and A[i] is at least 2, then it is a non-local global inversion.

    Reference:

    https://leetcode.com/problems/global-and-local-inversions/discuss/113656/My-3-lines-C%2B%2B-Solution

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Java static 关键字 静态初始化块
    一致性哈希
    Java函数传递方式值传递
    Scala 小练习
    Scala 推荐递归编程
    白话 Scala 控制抽象
    函数柯里化(curry)
    Scala 闭包 closure
    Scala 参数(类型)推断
    xcode配置文件中,Architectures表示的意义
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10661522.html
Copyright © 2011-2022 走看看