博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Contains Duplicate III
阅读量:6906 次
发布时间:2019-06-27

本文共 1446 字,大约阅读时间需要 4 分钟。

题目描写叙述:
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
就是给定1个数组nums,以及索引最大间隔k,和值最大间隔t。在nums数组内,找出是否存在num[i],和nums[j],当中i,j ∈[0,nums.Length-1]。使得 abs(i-j) <= k 而且 abs(nums[i]-nums[j]) <= t
思路:
1. 遍历nums数组,使用BST来存nums[i]在k范围内全部可达的数
2. 使用SortedSet<T>这个数据结构来存放从i到k范围内的每一个数,因为SortedSet的内部实现是平衡树
(http://stackoverflow.com/questions/3262947/is-there-a-built-in-binary-search-tree-in-net-4-0)。因此它的增删查都是log(n),所以算上外循环,整体复杂度是n*log(n)
3. 确定要查找的边界:
min = nums[i] - t; // 可取的最小值
max = nums[i] + t; // 可取的最大值
4. 假设sortedSet的长度大于 k。删除第一个。仅仅须要维护长度为k的数据就能够了
实现代码:
public class Solution {    public bool ContainsNearbyAlmostDuplicate(int[] nums, int k, int t) {    	if(k < 1 || t < 0){			return false;		}				if(nums == null || nums.Length == 1)    	{    		return false;    	}				var map = new SortedSet
(); for(var i = 0 ;i < nums.Length; i++) { if(nums[i] > Int32.MaxValue){ return false; } if(map.Count > k){ map.Remove(nums[i-k-1]); } var max = nums[i] + t; if(nums[i] > 0 && max < 0){ max = Int32.MaxValue; } var min = nums[i] - t; var found = map.GetViewBetween(min,max); if(found.Count > 0){ return true; } map.Add(nums[i]); } return false; }}

转载于:https://www.cnblogs.com/clnchanpin/p/6912482.html

你可能感兴趣的文章
SharePoint 2010 Performance Point Service Configuration and Utilization
查看>>
SSH连接不上的几个解决思路
查看>>
安卓IPC机制之Binder详解
查看>>
【python】python彻底卸载的方法【windows安装版卸载的示例】
查看>>
【maven + hibernate(注解) +spring +springMVC】 使用maven搭建项目
查看>>
微信浏览器关闭H5页面
查看>>
ANDROID开机动画分析
查看>>
Android 数字签名学习笔记
查看>>
以Lockbits的方式访问bitmap
查看>>
Javassist介绍
查看>>
Robot Framework 快速入门_中文版
查看>>
Java 开源博客——B3log Solo 0.6.0 正式版发布了!
查看>>
反射IsGenericType
查看>>
django 其他地址访问不了问题
查看>>
hibernate 需要的jar包
查看>>
Ubuntu 14.04 Remmina远程桌面连接Windows计算机
查看>>
iphone 判断某一目录是否包含文件夹
查看>>
[转载] iphone 创建iPhone锁定划动条的方法
查看>>
C# winfrom下绘制圆角窗体
查看>>
浏览器新开页面或刷新页面标志
查看>>