• 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)
  • 相关阅读:
    shell编程系列5--数学运算
    qperf测量网络带宽和延迟
    使用gprof对应用程序做性能评测
    [转]极不和谐的 fork 多线程程序
    Emacs显示光标在哪个函数
    Iterm2的一些好用法
    [转]最佳日志实践
    Deep Introduction to Go Interfaces.
    CGo中传递多维数组给C函数
    seaweedfs 源码笔记(一)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10661522.html
Copyright © 2020-2023  润新知