ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode 220 Contains Duplicate - zerteen

2020-03-07 10:55:58  阅读:270  来源: 互联网

标签:zerteen index hashmap nums 12Input Contains bucket Duplicate Example


Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

Example 1:

1
2
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

1
2
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

1
2
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

  • 使用hashmap来保存t个数
  • 将每个数模(t+1),将其放入对应的bucket中,那么每个bucket中的number的index差可定是在0-t之间的。
  • 对于相邻的两个bucket,也可能存在index差在0-t的number,一次,对于每个相邻的bucket,需要检查是否index差小于t
  • nums[i]可能是负数,若负数模(t+1),对应的bucket会错位,因此,nums[i]需要将其全部转换为正数,即nums[i]-Integer.MIN_VALUE;
  • 控制hashmap的item数目,来保证所求的index距离小于等于k
  • Corner case是k<1 || t < 0
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
class  

标签:zerteen,index,hashmap,nums,12Input,Contains,bucket,Duplicate,Example
来源: https://www.cnblogs.com/lijianming180/p/12433000.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有