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
题目大意:有N个数,大小范围是1-N-1,随意排列。global inversions是满足i<j&&A[i]>A[j]的总情况数。local inversions是A[i]>A[i+1]的情况总数。
如果二者相等,返回true,否则返回false。

初见题目,准备先求逆序数,再用O(n)的时间复杂度求A[i]>A[i+1]的总数,后来仔细想想,这样可能更麻烦。
思路一:
首先,local inversions一定是global inversions,但反过来就不一定成立。所以只需使是global inversions但不是local inversions的情况为0.首先,如果A[i]>A[i+1],那么就得使A[i]之前的所有数不得大于A[i+1],如果A[i]<A[i+1],那么也不能如此。所以只需A[i]之前的所有数不大于A[i+1]即可。那么就用一个for循环慢慢求最大值,一旦出现不满足的,就返回false。

代码:
class Solution {
public:
    bool isIdealPermutation(vector<int>& A) {
        int max=A[0];
        for(int i=1;i<A.size()-1;i++)
        {
            if(A[i+1]<max)
                return false;
             if(A[i]>max)
               max=A[i];
        }
        return true;
    }
};



思路二:
首先如果它们按照0,1,2……排列,那么local和global都是0,如果任意取相邻两个交换一下,那么local和global都是1。如果取不相邻的两个,那么就会多增加一个是global但不是local的。所以就不满足情况,对于多个数字进行交换的,只要存在交换后不相邻,那么就会出现是global而不是local。所以重新排列的数与它所在的位置之差不能大于1,可以等于1.
代码:
class Solution {
public:
    bool isIdealPermutation(vector<int>& A) {
        for(int i=0;i<A.size();i++)
        {
            if(abs(A[i]-i)>1)
                return false;
        }
        return true;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值