220. Contains Duplicate III
2016-03-15 17:11
369 查看
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.
解法:
这里的 t,k 均是大于0的,
用 set 保存当前位置前边的k个位置的数据,A: nums[i]
set 中的某个数据可用x表示。这里选用set的原因是 下边会用到求下界操作
则当满足下式时返回true
|x-A|<=t
-t<=x-A<=t
观察左半边:-t<=x-A,则满足条件的x>=A-t,即需要查找set中是否有大于或者等于(A-t)的数,如果有,则进行下一步判断。否则继续往后扫描数组。
如果set中有这样A-t的下界存在,假定这个数为X,
则满足:X-A<=t 时返回true
解法:
这里的 t,k 均是大于0的,
用 set 保存当前位置前边的k个位置的数据,A: nums[i]
set 中的某个数据可用x表示。这里选用set的原因是 下边会用到求下界操作
则当满足下式时返回true
|x-A|<=t
-t<=x-A<=t
观察左半边:-t<=x-A,则满足条件的x>=A-t,即需要查找set中是否有大于或者等于(A-t)的数,如果有,则进行下一步判断。否则继续往后扫描数组。
如果set中有这样A-t的下界存在,假定这个数为X,
则满足:X-A<=t 时返回true
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { int size=nums.size(); if(size<=1||k<=0) return false; set<int> table; for(int i=0;i<size;++i){ if(i>k){ table.erase(nums[i-k-1]); } auto it=table.lower_bound(nums[i]-t); if(it!=table.end()&&*it-nums[i]<=t) return true; table.insert(nums[i]); } return false; }
相关文章推荐
- PowerDesigner打开设计文件后提示failed to read the fileXXX的解决办法
- Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATI
- B - Pairs Forming LCM——(LightOJ 1236)
- mybaits中的<trim>标签的作用
- sakai创建工具的过程,以roster2为例
- IBM openblockchain学习(一)--obc-peer环境搭建
- 219. Contains Duplicate II
- sakai和jcloud操作流程
- 20160315 Sail Studio 2244 剪格子,2324 N^3,2230 K好数
- 配置Git的user name和email
- Bayesian Classifier (Naive Bayesian Classifier - 朴素贝叶斯分类)
- 应用环境下的TIME_WAIT和CLOSE_WAIT
- DTM initialization: failure during startup recovery, retry failed, check segment status (cdbtm.c:1603)
- 修复.MYI'; try to repair it
- LeetCode: Factorial Trailing Zeroes
- AIX 夏令时
- weblogic Unable to obtain lock on
- genymotion的 INSTALL_FAILED_CPU_ABI_INCOMPATIBLE
- CFNetwork SSLHandshake failed (-9847)