[leetcode][hash] Contains Duplicate III

原创 2015年07月08日 16:22:19

题目:

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.

分析:

1、维护一个长度为k的窗口

2.要满足条件|nums[j] - num[i]| <= t,即nums[j] >= nums[i]-t && nums[j] <= nums[i]+t;

set的lower_bound(nums[i]-t)函数可以找到大于等于nums[i]-t的最小数,如果该数小于nums[i]+t,那么这个数和nums[i]就是满足条件的数对。

3.注意这里有int数的相加,和可能越界,所以set必须使用long long型

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
	if (nums.size() < 2 || k <= 0 || t < 0) return false;
	int start = 0, end = 0;
	set<long long> hashTable;
	hashTable.insert(nums[0]);
	for (int i = 1; i < nums.size(); ++i){
		set<long long>::iterator iter = hashTable.lower_bound(nums[i] - t);
		if (iter != hashTable.end() && *iter <= (long long)nums[i] + t) return true;
		hashTable.insert(nums[i]);
		end = i;
		if (end - start == k){
			hashTable.erase(nums[start]);
			++start;
		}
	}
	return false;
}
};


相关文章推荐

Contains Duplicate III - LeetCode 220

题目描述: Given an array of integers, find out whether there are two distinct indices i and j in the ar...
  • bu_min
  • bu_min
  • 2015年06月01日 22:44
  • 421

[LeetCode] Contains Duplicate III

Contains Duplicate III Given an array of integers, find out whether there are two distinct indices ...

[leetcode ]220.Contains Duplicate III

题目: Given an array of integers, find out whether there are two distinct indices i and j in the arra...

[LeetCode]Contains Duplicate III

QuestionGiven an array of integers, find out whether there are two distinct indices i and j in the a...
  • byamao1
  • byamao1
  • 2017年02月16日 17:08
  • 77

LeetCode-Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array su...

【LEETCODE】220-Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array  ...

leetcode笔记--Contains Duplicate I & II & III

Contains Duplicate 题目:难度(Easy) Given an array of integers, find if the array contains any duplicat...

Leetcode 220. Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array suc...

【leetcode题解】【再看一遍】【86】【M】Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array suc...
  • sscssz
  • sscssz
  • 2015年12月17日 23:08
  • 185

《leetCode》:Contains Duplicate III

题目Given an array of integers, find out whether there are two distinct indices i and j in the array s...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:[leetcode][hash] Contains Duplicate III
举报原因:
原因补充:

(最多只允许输入30个字)