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)
  • 相关阅读:
    idea整合SVN以及SVN的使用
    解决svn检出后不显示图标的问题
    使用Nexus搭建Maven私服
    Idea中使用Maven
    初识Maven
    外网映射
    php 获取远程图片
    PHP中$_POST,$_GET,$_REQUEST,$_FILES全局变量的全局指什么
    linux定时执行文件
    PHP二维码生成的方法(google APi,PHP类库,libqrencode等)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10661522.html
Copyright © 2011-2022 走看看