zoukankan      html  css  js  c++  java
  • 775. Global and Local Inversions

    问题:

    给定一个由【0~N-1】组成的一个排列数组。

    local降序:相邻两个元素逆序。

    global降序:任意两个元素逆序。

    若该数组local降序数=global降序数,则返回true,

    反之返回false。

    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.
    

      

    解法1:

    该题即:所有元素只有相邻数逆序,则返回true

    那么,若第 i 个数 < 他前面隔一位(index:0~i-2)的最大值max1,即非相邻逆序情况数,至少有一个(那个最大值)(也有可能多于1个)

    这样的话,直接返回false即可。

    参考代码:

     1 class Solution {
     2 public:
     3     bool isIdealPermutation(vector<int>& A) {
     4         int max1=0;
     5         for(int i=1; i<A.size(); i++){
     6             if(A[i]<max1) return false;
     7             max1=max(max1, A[i-1]);
     8         }
     9         return true;
    10     }
    11 };

    解法2:

    由于该数组的特殊性为【0~n-1】的排序,

    若A[i]和他的index i 相差超过 1,那么有两种情况:

    1. A[i]-i > 1 : 如[2, 1, 0], A[0]-i=2-0 > 1,那么至少有两个小于A[0]=2的数在第0位后面。那么对于A[0]来说,global=2>local=1

    2. i-A[i] > 1 : 如[2, 1, 0], i-A[2]=2-0 > 1,那么至少有两个大于A[2]=0的数在第2位前面。那么对于A[2]来说,global=2>local=1

    参考代码:

    1 class Solution {
    2 public:
    3     bool isIdealPermutation(vector<int>& A) {
    4         for(int i=0; i<A.size(); i++){
    5             if(abs(A[i]-i)>=2) return false;
    6         }
    7         return true;
    8     }
    9 };
  • 相关阅读:
    连接数据库修改篇
    连接数据库
    get和post
    php连接mysql
    AJAX基础!
    JAVAsrcipt总结!
    使用AJAX如何得到数据库当中的值!
    AJAX如何做出输入框提示!
    PHP数据连接主键与外键!
    JAVA当中内存管理与垃圾回收!
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12856999.html
Copyright © 2011-2022 走看看