添加 problem 219

This commit is contained in:
YDZ
2019-05-07 19:04:24 +04:00
parent 27ae9ab5c4
commit a25d2e91fb
3 changed files with 106 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
package leetcode
func containsNearbyDuplicate(nums []int, k int) bool {
if len(nums) <= 1 {
return false
}
if k <= 0 {
return false
}
record := make(map[int]bool, len(nums))
for i, n := range nums {
if _, found := record[n]; found {
return true
}
record[n] = true
if len(record) == k+1 {
delete(record, nums[i-k])
}
}
return false
}

View File

@@ -0,0 +1,53 @@
package leetcode
import (
"fmt"
"testing"
)
type question219 struct {
para219
ans219
}
// para 是参数
// one 代表第一个参数
type para219 struct {
one []int
k int
}
// ans 是答案
// one 代表第一个答案
type ans219 struct {
one bool
}
func Test_Problem219(t *testing.T) {
qs := []question219{
question219{
para219{[]int{1, 2, 3, 1}, 3},
ans219{true},
},
question219{
para219{[]int{1, 0, 0, 1}, 1},
ans219{true},
},
question219{
para219{[]int{1, 2, 3, 1, 2, 3}, 2},
ans219{false},
},
}
fmt.Printf("------------------------Leetcode Problem 219------------------------\n")
for _, q := range qs {
_, p := q.ans219, q.para219
fmt.Printf("【input】:%v 【output】:%v\n", p, containsNearbyDuplicate(p.one, p.k))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,32 @@
# [219. Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/)
## 题目
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 absolute difference between i and j is at most k.
Example 1:
```c
Input: nums = [1,2,3,1], k = 3
Output: true
```
Example 2:
```c
Input: nums = [1,0,1,1], k = 1
Output: true
```
Example 3:
```c
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
```
## 题目大意
这是一道简单题,如果数组里面有重复数字,并且重复数字的下标差值小于等于 K 就输出 true如果没有重复数字或者下标差值超过了 K ,则输出 flase。
这道题可以维护一个只有 K 个元素的 map每次只需要判断这个 map 里面是否存在这个元素即可。如果存在就代表重复数字的下标差值在 K 以内。map 的长度如果超过了 K 以后就删除掉 i-k 的那个元素,这样一直维护 map 里面只有 K 个元素。