[LeetCode-interview algorithm classic-Java implementation] [219-Contains Duplicate II (including Duplicate element II)], leetcode -- java
[219-Contains Duplicate II (including Duplicate element II )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Download the Code [https://github.com/wang-jun-chao]Original question
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.
Theme
Given an integer array nums and an integer k, if two different subscripts I and j meet the requirements of nums [I] = nums [j] and | I-j | <= k, true is returned. Otherwise, false is returned.
Solutions
For nums [0... N-1], stored in a map, (muns [I], I), if the key nums [k] already exists, compare the difference between the previous subscript and the current lower mark, if the difference value is not greater than k, it indicates the two values that meet the condition. Otherwise, the new subscript is used as the value.
Code Implementation
Algorithm Implementation class
Import java. util. hashMap; import java. util. map; public class Solution {public boolean containsNearbyDuplicate (int [] nums, int k) {// if (nums = null | nums. length <2 | k <1) {return false;} Map <Integer, Integer> map = new HashMap <> (); for (int I = 0; I <nums. length; I ++) {// if no corresponding key is added to if (! Map. containsKey (nums [I]) {map. put (nums [I], I) ;}// there is already a subscript corresponding to the key-value Pair else {// The original saved value, it must be smaller than the current subscript int value = map. get (nums [I]); if (I-value <= k) {return true;} map. put (nums [I], I) ;}} return false ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note
Please refer to the source for reprinting [http://blog.csdn.net/derrantcm/article/details/48084061]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.