LeetCode-Contains Duplicate III-解题报告
2015-06-29 22:32
344 查看
原题链接https://leetcode.com/problems/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.
给你一个数组问是否存在索引i,j abs(i-j) <= k并且abs(nums[i] - nums[j]) <= t.
当然一眼看到,就会有一个最一般的算法,就是遍历去找,然而无情超时。
我使用的是随机算法,由于只是判断有没有,并不需要照出来。
所以我随机产生一个起点位置S, 然后再遍历S+K的范围内是否存在符合条件的情况,
符合,返回true;
不符合,重新产生起点位置S,重试50次(我随便输入的),都不符合返回false。
当然了这种方法存在侥幸的情况。后来看了别人的做法。
建立一个大小为K的最大堆
遍历数组,堆为空直接插入元素,如果堆的大小小于K,直接插入元素到数组,大于K,删除元素nums[i-(k +1)]
当前元素abs(nums[i] - max) <= t,return true;
遍历结束, return false
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (nums.empty())return false;
if (k == 0)return false;
srand(time(0));
for (int i = 0; i < 50; ++i)
{
int s = rand() % nums.size();
for (int j = s + 1; j <= s + k && j < nums.size(); ++j)
{
long long tmp = nums[s] - nums[j];
if (tmp >= 0 && tmp <= t)return true;
if (tmp < 0 && tmp*(-1) <= t)return true;
}
}
return false;
}
};
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 abs(i-j) <= k并且abs(nums[i] - nums[j]) <= t.
当然一眼看到,就会有一个最一般的算法,就是遍历去找,然而无情超时。
我使用的是随机算法,由于只是判断有没有,并不需要照出来。
所以我随机产生一个起点位置S, 然后再遍历S+K的范围内是否存在符合条件的情况,
符合,返回true;
不符合,重新产生起点位置S,重试50次(我随便输入的),都不符合返回false。
当然了这种方法存在侥幸的情况。后来看了别人的做法。
建立一个大小为K的最大堆
遍历数组,堆为空直接插入元素,如果堆的大小小于K,直接插入元素到数组,大于K,删除元素nums[i-(k +1)]
当前元素abs(nums[i] - max) <= t,return true;
遍历结束, return false
class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (nums.empty())return false;
if (k == 0)return false;
srand(time(0));
for (int i = 0; i < 50; ++i)
{
int s = rand() % nums.size();
for (int j = s + 1; j <= s + k && j < nums.size(); ++j)
{
long long tmp = nums[s] - nums[j];
if (tmp >= 0 && tmp <= t)return true;
if (tmp < 0 && tmp*(-1) <= t)return true;
}
}
return false;
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++中拷贝构造函数的应用详解
- C++中引用(&)的用法与应用实例分析
- C++使用CriticalSection实现线程同步实例
- C++智能指针实例详解
- 解析C++ 浮点数的格式化输出