当前位置:网站首页>220. Presence of repeating element III
220. Presence of repeating element III
2022-07-26 08:59:00 【apprentice.】
For this question , Because the question is limited abs(i - j) <= k Conditions , You should first think of sliding windows , Because sliding window can meet this limit . Conduct relevant operations on the data in the window to judge whether there is data in line with the meaning of the question
First, the size of the window should be k, This can meet the abs(i - j) <= k Conditions .
secondly , For the data in the window , You can use two for Loop to judge whether there is a combination that meets the meaning of the question . Because what is required in the question is the absolute value of subtraction , So for for loop , You can save half the cycle , because |a - b | = |b - a|
Here are Go The language code :
func containsNearbyAlmostDuplicate(nums []int, k int, t int) bool {
if k >= len(nums) {
k = len(nums) - 1
}
for start := 0; start+k < len(nums); start++ {
subArr := nums[start : start+k+1]
for i := 0; i <= k; i++ {
for j := i + 1; j <= k; j++ {
if abs(subArr[i]-subArr[j]) <= t {
return true
}
}
}
}
return false
}
func abs(num int) int {
if num < 0 {
return -num
}
return num
}
however , The time complexity of the implementation of violent solution is too high , Cause execution timeout
therefore , The time-consuming part of this algorithm needs to be optimized . For the optimization of the algorithm , Thinking is nothing more than the transformation of time and space . We want to reduce the time complexity , It can be done by increasing the spatial complexity .
Look back at the code above , The most time-consuming operation is to determine whether there is abs[i] - abs[j] <= t, For this operation , The above code uses the exhaustive method , The time complexity is O(n²), If we change to the idea of bucket sorting , The operation time complexity of this part can be reduced to O(n)
We can maintain multiple lengths t+1 The barrel , If two elements fall into a bucket at the same time , It means that the conditions in the question are met , If it falls into two adjacent barrels , You need to judge whether the absolute value of the subtraction of these two values meets the meaning of the question .
As shown in the following figure :
because t = 3 Then the number 0 - 3 Get a bucket ,4 -7 Get a bucket ,8 - 11 Get a bucket
For the first sliding window , Because the length is 3, So intercept the first three elements , These three elements correspond to three barrels
When putting the first element , Assigned to the first bucket , And there are no elements in the adjacent barrels .
When putting the second element , The first bucket next to it contains elements , but 5 - 1 > 3 So not satisfied
When putting the third element , The second bucket next to it contains elements , but 9 - 5 > 3 So not satisfied
And so on sliding window , Not satisfied until the end , So back false
Corresponding Go The code is as follows :
func containsNearbyAlmostDuplicate(nums []int, k, t int) bool {
mp := map[int]int{
}
for i, x := range nums {
id := getID(x, t+1)
if _, has := mp[id]; has {
return true
}
if y, has := mp[id-1]; has && abs(x-y) <= t {
return true
}
if y, has := mp[id+1]; has && abs(x-y) <= t {
return true
}
mp[id] = x
if i >= k {
delete(mp, getID(nums[i-k], t+1))
}
}
return false
}
func getID(x, w int) int {
if x >= 0 {
return x / w
}
return (x+1)/w - 1
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
For the above code , People who have seen it may have two questions :
1. For each barrel , Not saved in array , Instead, only one value is saved , Are you not afraid of being covered, which will cause other barrels to be adjacent to this barrel but not get the correct results ?
If coverage occurs here , Will go straight back to true Of , So there is no such situation .
2.getID about x<0 Some of them don't understand why .
For greater than 0 Part of , if t = 3 be 0-3,4-7,8-11... It's a group.
But for less than 0 Part of , In principle, it should be -4 - -1,-8 - -5 ... It's a group. , But if you follow x>=0 The method of calculation , be -4 And -1 Divided into two groups . So we need to +1, Turn it into -3 - 0 Keep consistent with positive numbers to group , After grouping -1, And 0-9 Medium 0 Make a difference . The result is just -4 - -1 This group
边栏推荐
- SSH,NFS,FTP
- PXE principles and concepts
- Regular expression: judge whether it conforms to USD format
- [untitled]
- Store a group of positive and negative numbers respectively, and count the number of 0 -- assembly language implementation
- sklearn 机器学习基础(线性回归、欠拟合、过拟合、岭回归、模型加载保存)
- 海内外媒体宣发自媒体发稿要严格把握内容关
- Huffman transformation software based on C language
- Replication of SQL injection vulnerability in the foreground of Pan micro e-cology8
- Dynamic SQL and exceptions of pl/sql
猜你喜欢
随机推荐
Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
[encryption weekly] has the encryption market recovered? The cold winter still hasn't thawed out. Take stock of the major events that occurred in the encryption market last week
Kotlin属性与字段
C#入门系列(三十一) -- 运算符重载
Web3 Games: current situation and future
Cadence(十)走线技巧与注意事项
The effective condition of MySQL joint index and the invalid condition of index
Day06 homework - skill question 7
Self review ideas of probability theory
After MySQL 8 OCP (1z0-908), hand in your homework
Set of pl/sql
数据库操作 技能6
OA项目之我的会议(查询)
Introduction to AWD attack and defense competition
Arbitrum Nova release! Create a low-cost and high-speed dedicated chain in the game social field
(1) CTS tradefed test framework environment construction
Center an element horizontally and vertically
Recurrence of SQL injection vulnerability in the foreground of a 60 terminal security management system
187. Repeated DNA sequence
Numpy Foundation