题目:

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 jis at most k.

链接: http://leetcode.com/problems/contains-duplicate-ii/

题解:

用HashMap来保存(nums[i],i) pair,假如存在相同key并且 i - map.get(key) <= k,返回true。否则遍历完毕以后返回false.

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if(nums == null || nums.length == 0)
return false;
Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) {
if(map.containsKey(nums[i])) {
if(i - map.get(nums[i]) <= k)
return true;
}
map.put(nums[i], i);
} return false;
}
}

二刷:

跟一刷一样,使用一个Map来保存数字以及数字的index,然后进行比较。假如相同并且 i - map.get(nums[i]) <= k,那么我们返回true。否则遍历完毕以后返回false.

Java:

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return false;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i]) && (i - map.get(nums[i]) <= k) ) {
return true;
}
map.put(nums[i], i);
}
return false;
}
}

三刷:

方法还是和一刷,二刷一样,用一个HashMap来保存元素和位置。这里最好给HashMap设定一个初始的大小来避免resizing带来的cost。最大的test case好像是30000,我们设置30000 / 0.75 = 40000左右就可以了。

Java:

Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || k <= 0) {
return false;
}
Map<Integer, Integer> map = new HashMap<>(41000);
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) {
return true;
}
map.put(nums[i], i);
}
return false;
}
}

使用Set以及sliding window。

  1. 我们维护一个size为k的HashSet
  2. 遍历整个数组,每次先判断是否有重复,有重复的话我们直接返回true
  3. 当size > k的时候,这时候size() = k + 1。 我们要把距离当前元素最远的一个元素,即第i - k个元素移出set,继续维护set的size = k
  4. 全部遍历完毕以后返回false。
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || k <= 0) {
return false;
}
Set<Integer> set = new HashSet<>();
for (int i = 0; i < nums.length; i++) {
if (!set.add(nums[i])) {
return true;
}
if (set.size() > k) {
set.remove(nums[i - k]);
}
}
return false;
}
}

Update:

利用HashMap的put。创建map的时候利用load factor = 0.75,我们建立一个比nums.length略大一些的map就能节约resizing的时间,但这也是空间换时间了。

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || k <= 0) return false;
Map<Integer, Integer> map = new HashMap<>((int)(nums.length / 0.8));
for (int i = 0; i < nums.length; i++) {
if (!map.containsKey(nums[i])) map.put(nums[i], i);
else if (i - map.put(nums[i], i) <= k) return true;
}
return false;
}
}

Update:重写了使用set的Sliding Window方法

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || k <= 0) return false;
Set<Integer> set = new HashSet<>((int)(nums.length / 0.8));
for (int i = 0; i < nums.length; i++) {
if (!set.add(nums[i])) return true;
if (set.size() > k) set.remove(nums[i - k]);
}
return false;
}
}

Update:  SouthPenguin的Sliding window方法。 最优解。

Worst case: Time Complexity - O(n), Space Complexity - O(n)

public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums == null || k <= 0) return false;
Set<Integer> set = new HashSet<>((int)(nums.length / 0.8));
for (int i = 0; i < nums.length; i++) {
if (i > k) set.remove(nums[i - k - 1]);
if (!set.add(nums[i])) return true;
}
return false;
}
}

Reference:

https://leetcode.com/discuss/38445/simple-java-solution

219. Contains Duplicate II的更多相关文章

  1. 219. Contains Duplicate II【easy】

    219. Contains Duplicate II[easy] Given an array of integers and an integer k, find out whether there ...

  2. 219. Contains Duplicate II - LeetCode

    Question 219. Contains Duplicate II Solution 题目大意:数组中两个相同元素的坐标之差小于给定的k,返回true,否则返回false 思路:用一个map记录每 ...

  3. [LeetCode] 219. Contains Duplicate II ☆(存在重复元素2)

    每天一算:Contains Duplicate II 描述 给出1个整形数组nums和1个整数k,是否存在索引i和j,使得nums[i] == nums[j] 且i和j之间的差不超过k Example ...

  4. [LeetCode] 219. Contains Duplicate II 包含重复元素 II

    Given an array of integers and an integer k, find out whether there are two distinct indices i and j ...

  5. [刷题] 219 Contains Duplicate II

    要求 给出整型数组nums和整数k,是否存在索引i和j,nums[i]==nums[j],且i和j之间的差不超过k 思路 暴力解法(n2) 建立最长为k+1的滑动窗口,用set查找窗口中是否有重复元素 ...

  6. LeetCode 219 Contains Duplicate II

    Problem: Given an array of integers and an integer k, find out whether there are two distinct indice ...

  7. Java for LeetCode 219 Contains Duplicate II

    Given an array of integers and an integer k, find out whether there there are two distinct indices i ...

  8. Leetcode 219 Contains Duplicate II STL

    找出是否存在nums[i]==nums[j],使得 j - i <=k 这是map的一个应用 class Solution { public: bool containsNearbyDuplic ...

  9. 【leetcode❤python】 219. Contains Duplicate II

    #-*- coding: UTF-8 -*-#遍历所有元素,将元素值当做键.元素下标当做值#存放在一个字典中.遍历的时候,#如果发现重复元素,则比较其下标的差值是否小于k,#如果小于则可直接返回Tru ...

  10. (easy)LeetCode 219.Contains Duplicate II

    Given an array of integers and an integer k, find out whether there there are two distinct indices i ...

随机推荐

  1. 一个简单的CS系统打包过程图文版

    一个简单的CS系统打包过程图文版 1.     打包内容 1.1.  此次打包的要求和特点 主工程是一个CS系统: 此CS系统运行的先决条件是要有.Net Framework 3.5: 主工程安装完成 ...

  2. rolling hash

    也是需要查看,然后修改,rolling hash, recursive hash, polynomial hash, double hash.如果一次不够,那就2次.需要在准备一个线段树,基本的线段树 ...

  3. IIS安装Web Deploy之后没有显示右键菜单

    Bug描述: 使用IIS自带的"Web平台安装程序"安装完Web Deploy组件之后,鼠标右键点击网站,弹出的菜单中并没有新增的"部署"选项. Bug解决: ...

  4. DigitalOcean(DO)购买VPS流程

    背景: 对于一个程序员来说,拥有自己的一台国外服务器是一种多么激动的事情,尽管配置不如自己电脑的1/5,但是想一想可以不用备案搭建网站,可以搭建shadow服务器,从此通过自己的服务器上网,想一想真是 ...

  5. javascript截取字符串(支持中英文混合)

    javascript截取字符串(支持中英文混合) <script type="text/javascript"> var sub=function(str,n){ va ...

  6. zhuan:点滴记录——Ubuntu 14.04中gedit打开文件出现中文乱码问题

    在中文支持配置还不完整的Ubuntu 14.04中,使用gedit打开带有中文字符的文件有时会出现乱码的情况,这是由于gedit对字符编码匹配不正确导致的,解决方法如下: 在终端中输入如下命令,然后重 ...

  7. C++数据类型总结

    关键字:C++, 数据类型, VS2015. OS:Windows 10. ANSI C/C++基本数据类型: Type Size 数值范围 无值型void 0 byte 无值域 布尔型bool 1 ...

  8. cc2640-各DEMO板性能分析

    一.测试方法: 将4种模块同时上电,测量每个模块达到的最远距离.以稳定能建立通讯为连接上依据.4种板子分析为 1号阿莫DEMO板,2号咱们自己DEMO板,3号嘉源电子DEMO,4号陆程电子DEMO 全 ...

  9. (转)Qt Model/View 学习笔记 (五)——View 类

    Qt Model/View 学习笔记 (五) View 类 概念 在model/view架构中,view从model中获得数据项然后显示给用户.数据显示的方式不必与model提供的表示方式相同,可以与 ...

  10. shell echo打印换行的方法

    echo要支持同C语言一样的\转义功能,只需要加上参数-e,如下所示: [~]#echo "Hello world.\nHello sea" Hello world.\nHello ...