当前位置:网站首页>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
边栏推荐
- C # use npoi to operate Excel
- Day06 homework - skill question 7
- OA项目之我的会议(查询)
- Oracle 19C OCP 1z0-082 certification examination question bank (36-41)
- 数据库操作技能7
- Solve the problem of C # calling form controls across threads
- Typescript snowflake primary key generator
- Datawhale panda book has been published!
- What are the differences in the performance of different usages such as count (*), count (primary key ID), count (field) and count (1)? That's more efficient
- [eslint] Failed to load parser ‘@typescript-eslint/parser‘ declared in ‘package. json » eslint-confi
猜你喜欢

Day06 operation -- addition, deletion, modification and query

合工大苍穹战队视觉组培训Day6——传统视觉,图像处理

One click deployment of lamp and LNMP scripts is worth having

数据库操作技能7

Set of pl/sql

Day06 homework -- skill question 2

Hegong sky team vision training Day6 - traditional vision, image processing

公告 | FISCO BCOS v3.0-rc4发布,新增Max版,可支撑海量交易上链

【数据库 】GBase 8a MPP Cluster V95 安装和卸载

JDBC数据库连接池(Druid技术)
随机推荐
【LeetCode数据库1050】合作过至少三次的演员和导演(简单题)
Espressif 玩转 编译环境
Center an element horizontally and vertically
Kotlin属性与字段
Pan micro e-cology8 foreground SQL injection POC
Database operation skills 6
[freeswitch development practice] use SIP client Yate to connect freeswitch for VoIP calls
Study notes of automatic control principle --- stability analysis of control system
数据库操作 题目二
After MySQL 8 OCP (1z0-908), hand in your homework
Uploading pictures on Alibaba cloud OSS
Which financial product has the highest yield in 2022?
03异常处理,状态保持,请求钩子---04大型项目结构与蓝图
[recommended collection] MySQL 30000 word essence summary + 100 interview questions (I)
The lessons of 2000. Web3 = the third industrial revolution?
NPM add source and switch source
海内外媒体宣发自媒体发稿要严格把握内容关
[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
P1825 [USACO11OPEN]Corn Maze S
at、crontab