Description
Given an array arr that represents a permutation of numbers from 1 to n. You have a binary string of size n that initially has all its bits set to zero.
At each step i (assuming both the binary string and arr are 1-indexed) from 1 to n, the bit at position arr[i] is set to 1. You are given an integer m and you need to find the latest step at which there exists a group of ones of length m. A group of ones is a contiguous substring of 1s such that it cannot be extended in either direction.
Return the latest step at which there exists a group of ones of length exactly m. If no such group exists, return -1.
Example 1:
Input: arr = [3,5,1,2,4], m = 1
Output: 4
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "00101", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "11101", groups: ["111", "1"]
Step 5: "11111", groups: ["11111"]
The latest step at which there exists a group of size 1 is step 4.
Example 2:
Input: arr = [3,1,5,4,2], m = 2
Output: -1
Explanation:
Step 1: "00100", groups: ["1"]
Step 2: "10100", groups: ["1", "1"]
Step 3: "10101", groups: ["1", "1", "1"]
Step 4: "10111", groups: ["1", "111"]
Step 5: "11111", groups: ["11111"]
No group of size 2 exists during any step.
Example 3:
Input: arr = [1], m = 1
Output: 1
Example 4:
Input: arr = [2,1], m = 2
Output: 2
Constraints:
- n == arr.length
- 1 <= n <= 10^5
- 1 <= arr[i] <= n
- All integers in arr are distinct.
- 1 <= m <= arr.length
分析
题目的意思是:给定一个数组arr和值m,arr里面的值代表相应的位置填1,求满足最近arr里面的值,这道题我虽然看懂了,但也是有点蒙圈。好想要找规律,对于arr长度等于m的情况,直接返回m;对于其他情况,维护一个border边界数组,对于当前遍历的数,找出其与左右边界的差值,如果等于m说明找到了一个满足条件的值,维护更新res,同时把border的左右边界更新一下。举例:
arr = [3,5,1,2,4], m = 1
[0, 0, 0, 3, 0, 0, 0]
[0, 0, 0, 3, 0, 5, 0]
[0, 1, 0, 3, 0, 5, 0]
[0, 3, 0, 1, 0, 5, 0]
[0, 5, 0, 1, 0, 1, 0]
arr = [3,1,5,4,2], m = 2
[0, 0, 0, 3, 0, 0, 0]
[0, 0, 0, 3, 0, 5, 0]
[0, 1, 0, 3, 0, 5, 0]
[0, 3, 0, 1, 0, 5, 0]
[0, 5, 0, 1, 0, 1, 0]
这个不好描述,自己模拟一下就明白了哈,我也是靠模拟,哈哈哈。我太难了。
代码
class Solution:
def findLatestStep(self, arr: List[int], m: int) -> int:
res=-1
border=[0]*(len(arr)+2)
for i,num in enumerate(arr):
l=r=num
if(border[r+1]>0):
r=r+1
if(border[l-1]>0):
l=l-1
border[l]=r
border[r]=l
if(r-num==m or num-l==m):
res=i
return res
代码二
class Solution:
def findLatestStep(self, arr, m: int):
if(len(arr)==m):
return m
res=-1
border=[0]*(len(arr)+2)
for i,num in enumerate(arr):
l=r=num
if(border[r+1]>0):
r=border[r+1]
if(border[l-1]>0):
l=border[l-1]
border[l]=r
border[r]=l
if(r-num==m or num-l==m):
res=i
print(border)
return res
if __name__ == "__main__":
solution=Solution()
arr = [3,5,1,2,4]
m = 1
res=solution.findLatestStep(arr,m)
print(res)
参考文献
[LeetCode] [Python] Short, boundary tracking for sets of ones, O(n)