LeetCode(220) Contains Duplicate III
2015-11-19 14:03
411 查看
题目
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.分析
题目描述:给定一个整数序列,查找是否存在两个下标分别为i和j的元素值|nums[i]−nums[j]|<t且满足i于j的距离最大为k;开始的时候,采取同 LeetCode(219) Contains Duplicate II的方法,元素值|nums[i]−nums[j]|<t的元素在set内遍历查找一遍,复杂度为O(n),很遗憾的超时了;
然后,查找资料,看到了另外一种简单的方法map解决方法:
使用map数据结构来解,用来记录数字和其下标之间的映射。 这里需要两个指针i和start,刚开始i和start都指向0,然后i开始向右走遍历数组,如果i和start之差大于k,且map中有nums[start],则删除并start加一。这样保证了map中所有的数的下标之差都不大于k,然后我们用map数据结构的lowerbound()函数来找一个特定范围,就是大于或等于nums[i]−t的地方,所有小于这个阈值的数和nums[i]的差的绝对值会大于t (可自行带数检验)。然后检测后面的所有的数字,如果数的差的绝对值小于等于t,则返回true。最后遍历完整个数组返回false。
AC代码
class Solution { public: //方法一,TLE bool containsNearbyAlmostDuplicate1(vector<int>& nums, int k, int t) { if (nums.empty()) return false; int sz = nums.size(); //使用容器unordered_set 其查找性能为常量 unordered_set<int> us; int start = 0, end = 0; for (int i = 0; i < sz; ++i) { int len = us.size(); for (int j = 0; j < len; ++j) { int tmp = abs(nums[j] - nums[i]); if (tmp <= t) return true; }//for us.insert(nums[i]); ++end; if (end - start > k) { us.erase(nums[start]); ++start; } }//for return false; } //方法二: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if (nums.empty()) return false; int sz = nums.size(); map<long long, int > m; int start = 0; for (int i = 0; i < sz; ++i) { if (i - start >k && m[nums[start]] == start) m.erase(nums[start++]); auto a = m.lower_bound(nums[i] - t); if (a != m.end() && abs(a->first - nums[i]) <= t) return true; //将元素值和下标插入map m[nums[i]] = i; }//for return false; return false; } };
GitHub测试程序源码
相关文章推荐
- Xcode6中如何去掉默认的Main.storyboard
- LeetCode(219) Contains Duplicate II
- LeetCode(219) Contains Duplicate II
- Archive failed
- Fibonacci Again模板
- mybatis 批量增加 Parameter '__frch_item_0' not found. Available parameters are [list]
- [1021]:Fibonacci Again
- AIDL中使用自定义类型时无法导包的问题
- FAL[server, ARC3]: FAL archive failed Error 16401 creating standby archive log file at host
- 测试用例 自动生成工具PICT与AllPairs
- 配置SharePoint 2013失败--Max Degree of Parallelism
- DELL T420塔式服务器RAID配置及OS安装
- HDU ACM 1789 Doing Homework again
- POJ 1273 Drainage Ditches
- ASP.NTE 5 Target framework dnx451 and dnxcore50(转)原文:http://www.cnblogs.com/xishuai/p/aspnet5-target-framework-dnx451-and-dnxcore50.html
- HackerRank "Minimum Average Waiting Time" !
- MVC中使用WebMail 发送注册验证信息
- 职责链模式(Chain of Responsibility Pattern)
- Genymotion 2.5.4: Unable to create virtual device : Failed to import OVA file
- CrossDomain.xml的作用及其简单用法