Contains Duplicate II
来自 <https://leetcode.com/problems/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 jis at most k.
题目解读
给定一个整型数组和整数k,找出数组中是否存在不同的i和j,使得nums[i] = nums[j] ,并且i与j之间的距离最大是k。
解析
使用set,逐个向set中添加元素,使set中的元素个数小于k个。当set中的元素达到k个的时候,将在set中最早加入的删除,然后再向set中添加元素。
Java代码:
public boolean containsNearbyDuplicate(int[] nums, int k) { if(null == nums) return false; Set<Integer> result = new HashSet<Integer>(); int start = 0; int end =0; for(int i=0; i<nums.length; i++) { if(result.contains(nums[i])) { return true; } else { result.add(nums[i]); end++; } if((end - start) > k){ result.remove(nums[start]); start++; } } return false; }
算法性能:
相关推荐
contains-duplicate-0217 find-minimum-in-rotated-sorted-array-0153 数组的乘积-除了-self-0238 从排序数组中删除重复项-0026 搜索旋转排序数组-0033 两个整数之和-0371 二和-0001 回溯 组合-和-0039 组合总和-ii-...
java lru leetcode leetcode-java leetcode刷题笔记 已做题目列表 1.Two Sum 3.Longest Substring Without Repeating Characters ...II ...II ...217.Contains Duplicate 263.Ugly Number 264.Ugly Number II
Leetcode的ac是什么意思 LeetCodeInJava List #98 Validate Binary Search Tree #100 Same Tree #104 Maximum Depth of Binary Tree #122 Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate ...
“contains_duplicate.py” - 检查整数列表是否包含任何重复项的快速算法。 “contains_nearby_duplicate.py” - 检查整数列表是否包含距离 k 内的任何重复项的快速算法。 "coin_arrangement.py" - 给定 n,算法找到...
462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/...
leetcode下载 algorithm_reearch algorithm_reearch 链表 leetcode: 146 有无环 双向链表,删除 写大于读的情形 LinkedHashMap与 LRU算法 基于访问时间的链表 或者 基于插入时间的链表 哈希表: leetcode: 1. two sum...
Contains Duplicate (E) 48. Rotate Image (M) -> 2 73. Set Matrix Zeroes (M) 1. Two Sum (E) 167. Two Sum II - Input array is sorted (E) 653. Two Sum IV - Input is a BST (E) -> 2 26. Remove Duplicates ...
leetcode 浇花力扣解决方案 简单的 #0001 - Two Sum #0007 - Reverse Integer #0009 - Palindrome Number #0035 - Search Insert Position #0058 - Length of Last Word #0066 - Plus One #0083 - Remove Duplicates...
leetcode 答案Leet Code 挑战 这是我提交给 Lambda School CS Unit 2 构建周的已接受 ...Duplicates](https://leetcode.com/problems/contains-duplicate/) [x] [Linked List Cycle II](https://leetcode.co
leetcode leetcode_java prepare for jobhunting. java version of Leetcode. easy 55 about takes 5 days medium 112 about takes 20 days hard 48 about take 10 days Summarize and implement all sort ...
Contains Duplicate II Contains Duplicate III Product of Array Except Self Game of Life Increasing Triplet Subsequence 单链表 Reverse Linked List Odd Even Linked List Add Two Numbers Reverse Linked ...