您的位置:首页 > 大数据 > 人工智能

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode