220. Contains Duplicate III

来源:互联网 发布:丽水领导干部网络学校 编辑:程序博客网 时间:2024/05/15 23:45

题目:包含重复值3

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] andnums[j] is at most t and the difference between i and j is at most k.


题意:

给定一个整数数组,判断其中是否存在两个不同的下标i和j满足:| nums[i] - nums[j] | <= t 并且 | i - j | <= k。


思路一:

使用map数据结构来解,用来记录数字和其下标之间的映射。 这里需要两个指针i和j,刚开始i和j都指向0,然后i开始向右走遍历数组,如果i和j之差大于k,且m中有nums[j],则删除并j加一。这样保证了m中所有的数的下标之差都不大于k,然后我们用map数据结构的lower_bound()函数来找一个特定范围,就是大于或等于nums[i] - t的地方,所有小于这个阈值的数和nums[i]的差的绝对值会大于t (可自行带数检验)。然后检测后面的所有的数字,如果数的差的绝对值小于等于t,则返回true。最后遍历完整个数组返回false。

代码:60ms

class Solution {public:    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {        map<int, int> m;        int j = 0;        for (int i=0; i<nums.size(); ++i) {            //维持一个大小为k的窗口,大于该窗口时,擦除掉第一个值            if (i-j > k && m[nums[j]]==j) m.erase(nums[j++]);            //通过m.lower_bound(nums[i] - t)找到在map中刚好比nums[i] - t大一点儿的值的下标            auto a = m.lower_bound(nums[i] - t);             //满足条件,返回true            if (a!=m.end() && abs(a->first - nums[i]) <= t) return true;            m[nums[i]] = i;        }        return false;    }};


思路二:

使用桶排序。

代码:25ms

public class Solution {    public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {        if (k<1 || t<0) return false;        Map<Long, Long> map = new HashMap<>();        for (int i=0; i<nums.length; i++) {            long remappedNum = (long)nums[i] - Integer.MIN_VALUE;            long bucket = remappedNum/((long)t + 1);            if (map.containsKey(bucket)                 || (map.containsKey(bucket-1) && remappedNum-map.get(bucket-1)<=t)                || (map.containsKey(bucket+1) && map.get(bucket+1)-remappedNum<=t))                return true;            if (map.entrySet().size() >= k) {                long lastBucket = ((long) nums[i-k]-Integer.MIN_VALUE)/((long)t+1);                map.remove(lastBucket);            }            map.put(bucket, remappedNum);        }        return false;    }}


1 0
原创粉丝点击