【Leetcode】Contains Duplicate II #219

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

url:https://leetcode.com/problems/contains-duplicate-ii/

1.将nums[0..k-1]放入hashset中

2.nums[i | i = k..size-1], 每次检查nums[i]是否在hashset中。如存在, 则返回。如不存在,将hashset中最早的element清除,并加入nums[i]。set中始终有k-1个element

注意:以上思路基于size > k,故需要在第一个循坏加入bound,确保不会越界

bool containsNearbyDuplicate(vector<int>& nums, int k) {
	unordered_set<int> set;
	unsigned long size = nums.size();
	
	int bound = min(k,(int)size);
	for (int i = 0; i < bound; ++i){
	  if (set.count(nums[i]) > 0)
		return true;
	  else 
		set.insert(nums[i]);
	}


	for (int i = k; i < size; ++i)
	{
		if (set.count(nums[i]) > 0)
			return true;
		else{
		  set.insert(nums[i]);
		  set.erase(nums[i-k]);
		}
	}
	return false;
}

看到一个C code的答案很有意思,利用array来记录位置。但是不适用于给定数据有负数的情况

#define MAX 99999
bool containsNearbyDuplicate(int* nums, int numsSize, int k) {
       int arr[MAX];
    if (k==0) {
        return false;
    }
    for (int i=0; i<MAX; i++) {
        arr[i] = -1;
    }
    for (int i=0; i<numsSize; i++) {
        if (arr[nums[i]] == -1) {
            arr[nums[i]] = i;
        } else {
            if (abs(arr[nums[i]] - i) <=k) {
                return true;
            }
            arr[nums[i]] = i;
        }
    }
    return false;
}
因为i肯定大于arr[nums[i]],abs可以省略替换为:i - arr[nums[i]] 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值