【Leetcode】Contains Duplicate II #219

来源:互联网 发布:域名备案ps 编辑:程序博客网 时间:2024/05/21 14:55

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 99999bool 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]] 

0 0