[LeetCode]--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 difference between i and j is at most k

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

想法:这题比较简单,可以直接定义一个长度最大为k的滑动窗口,用一个set维护窗口内的数字判断是否出现重复,使用两个指针start和end标记滑动窗口的两端,初始都是0,然后end不断进行扩展,扫描元素判断是否出现重复元素,直到发现end-start>k, 就开始移动start,并且在set中移除对应的元素。如果以为扫描到数组末尾还没有发现重复元素,那就可以返回false。时间复杂度和空间复杂度都是O(N)。

Set<Integer> appearedNum = new HashSet<Integer>();
        int start = 0, end = 0;
        for (int i = 0; i < nums.length; i++) {
            if (!appearedNum.contains(nums[i])) {
                appearedNum.add(nums[i]);
                end++;
            } else
                return true;
            if (end - start > k) {
                appearedNum.remove(nums[start]);
                start++;
            }
        }
        return false;
目录
相关文章
|
索引
LeetCode 287. Find the Duplicate Number
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
90 0
LeetCode 287. Find the Duplicate Number
[LeetCode]--63. Unique Paths II
Follow up for “Unique Paths”: Now consider if some obstacles are added to the grids. How many unique paths would there be? An obstacle and empty space is marked as 1 and 0 respectively in
1036 0
[LeetCode]--71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. For example, path = “/home/”, =&gt; “/home” path = “/a/./b/../../c/”, =&gt; “/c” click to show corner cases. Corner Cases:
1066 0
|
机器人
[LeetCode]--62. Unique Paths
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to r
988 0
[LeetCode]--49. Group Anagrams
Given an array of strings, group anagrams together. For example, given: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”], Return: [ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ] Note
1105 0
[LeetCode]--217. Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every
1509 0
[LeetCode]--383. Ransom Note

Given
 an 
arbitrary
 ransom
 note
 string 
and 
another 
string 
containing 
letters from
 all 
the 
magazines,
 write 
a 
function 
that 
will 
return 
true 
if 
the 
ransom 
 note 
can
1335 0
[LeetCode]--389. Find the Difference
Given two strings s and t which consist of only lowercase letters. String t is generated by random shuffling string s and then add one more letter at a random position. Find the letter th
1222 0