前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Array - 219. Contains Duplicate II

Array - 219. Contains Duplicate II

作者头像
ppxai
发布2020-09-23 17:07:59
2630
发布2020-09-23 17:07:59
举报
文章被收录于专栏:皮皮星球皮皮星球

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 absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3 Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1 Output: true

思路:

这题是217题的变形,多加了在k范围内重复才返回true,思路也是使用map来做,遍历的同时查重,时间复杂度O(N),空间复杂度为O(N),使用滑动窗口的思想可以优化空间复杂度为O(K)。

代码:

java:

class Solution {

    // solution 1 hashmap. time: O(n) space: O(n)
    /*public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length == 0) return false;
        
        HashMap<Integer, Integer> map = new HashMap();
        for (int i = 0;  i < nums.length; i++) {
            Integer index = map.get(nums[i]);
            if (index != null && i-index <= k){
                return true;
            }
            
            map.put(nums[i], i);
        }
        
        return false;
    }*/
    
    // solution 2 Sliding Window. time: O(n) space: O(k)
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums == null || nums.length == 0) return false;
        
        HashSet<Integer> set = new HashSet();
        for (int i = 0;  i < nums.length; i++) {
           if (!set.add(nums[i])) {
               return true;
           }
            
           // 更新set,保证大小不超过k
           if (i >= k) {
               set.remove(nums[i - k]);
           }
        }
        
        return false;
    }
  
} // best case

go:

/*func containsNearbyDuplicate(nums []int, k int) bool {
    if nums == nil || len(nums) == 0 { return false }

    var (
        maps   = make(map[int]int)
        window = make([]int, 0) 
    )
    
    for i, v := range nums {
        if _, ok := maps[v]; ok{
            return true
        } else {
            maps[v] = i
            window = append(window, v)
        }
        
        // update map size if we have more than k
        if (i >= k) {
            delete(maps, window[0])
            window = window[1:]
        }
    }
    
    return false 
}
//bad case */

func containsNearbyDuplicate(nums []int, k int) bool {
    exist := make(map[int]int, len(nums))
    for i, v := range nums{
        if pos, ok := exist[v]; ok && i - pos <= k{
            return true
        }
        exist[v] = i
    }
    return false
}```
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019年06月12日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档