【发布时间】:2017-09-25 03:12:28
【问题描述】:
问题陈述:
给定 N*N 矩阵,矩阵中的每个单元格都包含警察或小偷。
找出被警方逮捕的小偷人数。
- 警察只能逮捕一个小偷。
- 警察可以在同一排逮捕小偷。
- 警察可以在K范围内抓小偷。(例如:如果K为1,那么3号牢房的警察只能抓2号和4号牢房的小偷)
输入:
3 1 -> 这里 3 是 N, 1 是 K
呸呸呸
T T P
呸呸呸
输出:
3
我的解决方案因某些输入而超时:
1. Iterate each row and have two Treeset<Integer> to store position of police and thief
2. If current item is Police, then check if thief Treeset is Not empty,
a.if so then iterate the treeset to find the position from thief set which
can be removed(satisfying above criteria), remove thief from treeset and
increment counter.
a.1. If such item not available then add current position to police set
b. if not then add position to police treeset
3. If current item is Thief, then do the same
在对一行完成迭代后,对下一行进行迭代,最后打印计数器。
取一行的时间复杂度:
1. 迭代行中的每个元素 O(n)
2. 从树集中添加或删除元素 O(log(n))
肯定需要超过 O(n*log(n))
请告诉我这是什么类型的问题以及我应该如何有效地解决。
【问题讨论】:
-
对 N(矩阵大小)有什么限制?
-
提示:解决方案应该是
O(N^2)。有 N^2 个单元格,每个单元格必须至少检查一次。但我认为您不需要检查单元格超过恒定次数。 (基于我脑海中的算法:-))这意味着O(N^2)。 -
现在如果给你警察的职位,
O(P)的解决方案可能是可能的......其中P是警察的人数。 (这也是基于矩阵的问题的一点提示。) -
好吧,现在我注意到外面,有完全相同的问题(确切的措辞)......很有可能是那些在线比赛的一些问题,是吗?stackoverflow.com/questions/46397308/…跨度>
-
是的,同一个,在线测试中