题目:

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. 设置图层符号风格为用已有mxd里的同名图层风格

    //要加载的IFeatureClass IFeatureClass pFeatClass = dataset as IFeatureClass; //新建要加载到mxd文档中的图层 IFeatureL ...

  2. 鼠标按键自定义软件-X-Mouse Button Control

    转载说明 本篇文章可能已经更新,最新文章请转:http://www.sollyu.com/mouse-button-x-mouse-button-custom-software-control/ 说明 ...

  3. map容器按value值排序

    1 vector<pair<key,value> >类型的容器中存放所有元素,sort(pair默认按照value比较大小?) 2 map<value,key>

  4. 按按钮调用PHP function函数

    首先,请大家看一段HTML代码: <html> <head> </head> <body> <input type=button on_click ...

  5. 3月3日[Go_deep]Populating Next Right Pointers in Each Node

    原题:Populating Next Right Pointers in Each Node 简单的链表二叉树增加Next节点信息,没什么坑.不过还是WA了两次,还是有点菜,继续做,另外leetcod ...

  6. Poj OpenJudge 百练 1573 Robot Motion

    1.Link: http://poj.org/problem?id=1573 http://bailian.openjudge.cn/practice/1573/ 2.Content: Robot M ...

  7. 关于webview嵌入swf

    有的机子CPU不支持swf播放的,不知道你是不是中奖了.. webview 加载swf很简单:         if(versionDouble>=2.2){//版本低于2.2的系统无法播放sw ...

  8. 如何禁止KnockoutJs在VS2012的智能格式化

    http://blogs.msdn.com/b/webdev/archive/2013/03/04/disabling-knockout-intellisense.aspx 我升级了一下VS2012, ...

  9. OpenCV3读取视频或摄像头

    我们可以利用OpenCV读取视频文件或者摄像头的数据,将其保存为图像,以用于后期处理.下面的实例代码展示了简单的读取和显示操作: // This is a demo introduces you to ...

  10. asp.net 时间比较,常用于在某段时间进行操作

    DateTime.Compare(t1,t2)比较两个日期大小,排前面的小,排在后面的大,比如:2011-2-1就小于2012-3-2返回值小于零:  t1 小于 t2. 返回值等于零 : t1 等于 ...