练习题 (九)
2015-07-03 16:47
323 查看
题目:
解答:
心得:这里的需要用到set容器,然后最初的先排序,再找出距离最远的两个数,看两个数的差距有没有大于等于t,这个想法,进化为用low_bound()函数来实现。
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。
Contains Duplicate III
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.解答:
class Solution { public: bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { if ((nums.size() < 2) || (k <= 0) || (t < 0)) { return false; } // This multiset is essentially a BST which stores all the numbers // within the window of size k + 1. Note that we have to use long // instead of int since we have to handle the possible overflow of // nums[i] + t. multiset<long> numBst; for (int i = 0; i < nums.size(); i++) { if (i >= k + 1) { // Delete the number which falls out of the window of size k + 1. auto itDelete = numBst.find(static_cast<long>(nums[i - (k + 1)])); numBst.erase(itDelete); } // Check whether numBst contains some number between nums[i] - t // and nums[i] + t (inclusive). auto itLower = numBst.lower_bound( static_cast<long>(nums[i]) - static_cast<long>(t)); if ((itLower != numBst.end()) && (*itLower <= static_cast<long>(nums[i]) + static_cast<long>(t))) { return true; } // Insert nums[i] into the BST. numBst.insert(static_cast<long>(nums[i])); } return false; } };
心得:这里的需要用到set容器,然后最初的先排序,再找出距离最远的两个数,看两个数的差距有没有大于等于t,这个想法,进化为用low_bound()函数来实现。
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。
相关文章推荐
- 分布式流式计算平台——S4
- java中浮点数的差结果无法预测,其他语言好像也有这种结果
- DRBD+HEARTBEAT+NFS简要命令记录
- 从终端获取一个字符串,分别统计其中大写字母、小写字母、数字及其它字符的个数。
- C++ primer学习笔记(5)——vector中装的是string指针怎么办
- 连汇顶PC端烧写工具手机崩溃分析
- XCode快捷键
- PHP PSR-1 基本代码规范(中文版)
- IHttpActionResult不识别解决办法
- 距离和相似度度量
- xtrabackup 源码安装
- JAVA虚拟机内存回收算法与调优参数
- 东莞莫仕连接器实现文控管理
- iOS编程 CALayer 自定义层对象并添加 第二种方法
- 字典树
- 自定义PropertyGrid控件【转】
- Kmeans算法与KNN算法的区别
- android LinearLayout添加分隔线
- android应用实现自动升级从本地服务器,通过一个工具类
- leetcode | Path Sum II