Contains Duplicate 包含重复

217. Contains Duplicate

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

class Solution {
public:
	bool containsDuplicate(vector<int>& nums) {

		int len = nums.size();
		if (len <= 1){
			return false;
		}

		unordered_set<int> s;
		for (int i : nums){
			if (s.count(i)){
				return true;
			}
			else{
				s.insert(i);
			}
		}
		return false;
	}
};


219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and j is at most k.

最初想法是用map<int,vector<int>>记录值和相应的索引,最后发现没有必要啊,i从0遍历到len-1是依次增大的,记录某值最大的i即可。

class Solution {
public:
	bool containsNearbyDuplicate(vector<int>& nums, int k) {
		map<int, int> m;
		int len = nums.size();
		for (int i = 0; i < len; i++){
			if (m.count(nums[i])){
				if (i - m[nums[i]] <= k){
					return true;
				}
			}
			m[nums[i]] = i;
		}
		return false;
	}
};

220. 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) {
		int len = nums.size();
		for (int i = 0; i < len; i++){
			for (int j = i + 1; j <= i + k && j < len; j++){
				long long a = nums[i];
				long long b = nums[j];
				long long diff = a>b ? (a - b) : (b - a);
				if (diff <= t){
					return true;
				}
			}
		}
		return false;
	}
};
超时


下面有一巧妙的算法:

1.首先维持一个大小为k的multiset,即相当于滑动窗口;

2.对于nums[i],找窗口中 p=ms.lower_bound(nums[i] - t) ,即是不小于nums[i] - t的数的迭代器;

3.*p可能不存在,有可能小于nums[i],也有可能大于nums[i];

    小于时,存在即可返回true;

    大于时,*p-nums[i]<=t 即可返回true

所以总的判断

if (p != ms.end()&& *p-nums[i]<=t)

class Solution {
public:
	bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
		int len = nums.size();
		multiset<long long> ms;
		for (int i = 0; i < len; i++){
			if (ms.size()>k){
				ms.erase(nums[i - k - 1]);
			}

			auto p = ms.lower_bound(nums[i] - t);
			if (p != ms.end()&& *p-nums[i]<=t){
				return true;
			}

			ms.insert(nums[i]);
		}
		return false;
	}
};





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值