1. Topic
Given an array of integers nums
and an integer k
, determine whether there are two different index sums in the array , satisfying and . If it exists, return it ; otherwise, return it . i
j
nums[i] == nums[j]
abs(i - j) <= k
true
false
2. Examples
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false
hint
1 <= nums.length <= 105
-109 <= nums[i] <= 109
0 <= k <= 105
3. Ideas
Hash table:
First of all, seeing that the index and the corresponding value need to be used in the array, it is obvious to think of the hash table data structure and related search to reduce the search speed. By traversing the array, the data that does not exist in the table and the corresponding index are stored in the In the hash table, if you encounter the existing key-value data, find the index of the data and subtract the absolute value from the value currently traversed to obtain the result and make a judgment. If it matches, return true. If the end of the traversal is not satisfied, return false
4. Code
LeetCode code
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int temp;
HashMap<Integer,Integer> map = new HashMap<>();
for (int i=0;i< nums.length;i++){
if (map.containsKey(nums[i])){
temp = map.get(nums[i]);
if (Math.abs(temp-i)<=k){
return true;
}
}
map.put(nums[i],i);
}
return false;
}
}
Time complexity is O(n), O(1)
Case detailed code:
package LeetCode18;
import java.util.HashMap;
public class javaDemo {
public static void main(String[] args) {
int nums[]= new int[]{1,2,3,1};
int k = 3;
// 中间量
int temp;
boolean flag = false;
// 创建哈希表
HashMap<Integer,Integer> map = new HashMap<>();
// 循环遍历
for (int i=0;i< nums.length;i++){
// 查找是否已经存在一样的值
if (map.containsKey(nums[i])){
temp = map.get(nums[i]);
// 判断两者绝对值差值是否小于等于k
if (Math.abs(temp-i)<=k){
flag = true;
break;
}
}
// 如果不存在键则把键值都存放到哈希表
map.put(nums[i],i);
}
// 输出结果
System.out.println(flag);
}
}
Will it? Try to challenge the next question! ♪(^∀^●)ノシ(●´∀`)♪
LeetCode 150 interview classic questions -- happy number (simple)_Alphamilk's Blog-CSDN Blog