【LeetCode】775. Global and Local Inversions 解题报告(Python)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址: https://leetcode.com/problems/global-and-local-inversions/description/
题目描述:
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.
题目大意
如果存在i < j
with 0 <= i < j < N
and A[i] > A[j]
,称之为一个全局翻转。
如果存在0 <= i < N
and A[i] > A[i+1]
,称之为一个局部翻转。
判断一个由0~N - 1组成的一个乱序数组中,全局翻转的个数与局部翻转的个数是否相等。
解题方法
首先当j = i + 1时,可以看出,一个局部翻转就是一个全局翻转。那么如果要使得局部翻转和全局翻转的个数相等,那么必须要求全局翻转也是一个局部翻转。所以,对于任意的j > i + 1,不能存在A[i] > A[j],即需要满足A[i] <= A[j].
从上面的关系可以看出,我们必须使max(A[:i]) <= A[i + 2]。
最坏情况下的时间复杂度是O(N),空间复杂度是O(1)。
class Solution(object):
def isIdealPermutation(self, A):
"""
:type A: List[int]
:rtype: bool
"""
cmax = 0
for i in range(len(A) - 2):
cmax = max(cmax, A[i])
if cmax > A[i + 2]:
return False
return True
上面的想法并没有好好的利用题目给出的数字是0N-1这个条件。所以我们继续思考,如果原来的顺序是0N-1,那么如何交换两个数字才能满足局部翻转的个数等于全局翻转呢?答案当然是只翻转相邻的两个元素。否则会构造出来一个不是局部翻转的全剧翻转。所以i的位置上只能放A[i-1],A[i],A[i+1]。
class Solution(object):
def isIdealPermutation(self, A):
"""
:type A: List[int]
:rtype: bool
"""
for i, a in enumerate(A):
if abs(a - i) > 1:
return False
return True
参考资料:
日期
2018 年 10 月 1 日 —— 欢度国庆!
最新文章
- mysql数据库视图连接出现2003&#183;&#183;&#183;&#183;错误
- Linux-wget
- [BS-25] IOS中手势UIGestureRecognizer概述
- Java笔记--java一行一行写入或读取数据
- coding.net解决github上下载速度慢问题
- SQL AlawaysOn 之五:ISCSI共享磁盘
- python--DenyHttp项目(1)--socket编程:服务器端进阶版socketServer
- 【Java基础】【25多线程(下)&;GUI】
- 必做课下作业MyCP
- SpringBoot无废话入门03:SpringMVC支持
- HTTP请求报文和响应报文
- component 理解
- 二次注入的学习--Buy Flag(http://10.112.68.215:10002)
- Spring源码分析:非懒加载的单例Bean初始化过程(下)
- C#中byte[] 转 double[] 或 int[] 或 struct结构体
- 没有添加spring mvc 默认依赖包产生的错误
- Springmvc中的HandlerAdaptor执行流程
- OpenERP的短信(SMS)接口
- DBMS_LOB的简单用法以及释放DBMS_LOB生成的临时CLOB内存
- 从Objective-C到Swift,你必须会的(三)init的顺序