"219-contains Duplicate II (contains repeating element II)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
code Download "Https://github.com/Wang-Jun-Chao"
Original Question
Given an array of integers and a integer k, find out whether there is II distinct indices I and j in the array such tha T nums[i] = Nums[j] and the difference between I and J are at most K.
Main Topic
Given an integer array nums with an integer k, returns False if and only if there are two different subscript I and J satisfies nums[i] = Nums[j] and |i-j|<=k returns TRUE.
Thinking of solving problems
For nums[0...n-1], deposited in a map, (Muns[i], i), if the key nums[k] already exists, then compare the previous subscript and now the difference between the subscript, if the difference is not greater than k, indicating that the condition is satisfied with the two values, otherwise use the new subscript as the value
Code Implementation
Algorithm implementation class
Import Java.util.hashmap;import Java.util.Map; Public classSolution { PublicBooleancontainsnearbyduplicate(int[] Nums,intK) {//Input condition judgment if(Nums = =NULL|| Nums.length <2|| K <1) {return false; } map<integer, integer> Map =NewHashmap<> (); for(inti =0; i < nums.length; i++) {//If there is no corresponding key to add in if(!map.containskey (Nums[i])) {Map.put (nums[i], i); }//already have a corresponding key-value to Else{//The original saved value corresponding to the subscript, it must be smaller than the current subscript int value= map.Get(Nums[i]);ifIvalue<= k) {return true; } map.put (Nums[i], i); } }return false; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/48084061"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java Implementation" "219-contains Duplicate II (contains duplicate element II)"