-
Notifications
You must be signed in to change notification settings - Fork 0
/
contains-duplicate-ii.go
55 lines (51 loc) · 1.17 KB
/
contains-duplicate-ii.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"fmt"
)
// Given an array of integers and an integer k,
// find out whether there are two distinct indices i and j in the array
// such that nums[i] = nums[j] and the difference between i and j is at most k.
func containsNearbyDuplicate(nums []int, k int) bool {
length := len(nums)
if length <= 1 || k <= 0 {
return false
}
valueMap := make(map[int][]int) // v: []i
for i, v := range nums {
s, ok := valueMap[v]
if !ok {
s = []int{i}
} else {
s = append(s, i)
}
valueMap[v] = s
}
fmt.Println("nums= ", nums)
for _, v := range valueMap {
length := len(v)
if length <= 1 {
continue
}
fmt.Println("==================== v = ", v)
for i := 0; i < length-1; i++ {
for j := i + 1; j < length; j++ {
if findDifference(nums, v[i], v[j]) <= k {
return true
}
}
}
}
return false
}
func findDifference(nums []int, begin int, end int) int {
result := make(map[int]int)
for i := begin; i <= end; i++ {
result[nums[i]]++
}
fmt.Println(begin, end, result)
return len(result)
}
func main() {
// fmt.Println(containsNearbyDuplicate([]int{99, 99}, 2))
fmt.Println(containsNearbyDuplicate([]int{1, 2, 1, 1}, 1))
}