219. Contains Duplicate II
5.28号群里的附加题
- 题目
- 翻译
- 思路和解题过程
- 代码及验证图
题目
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 absolute difference between i and j is at most k.
翻译
给定整数数组和整数k,找出数组中是否有两个不同的索引i和j,使得
nums [i] = nums [j],
i和j之间的绝对差值最多为k。
思路和解题过程
作为一个新手= =第一眼看到就准备用最傻瓜朴素的方法来解啦..
然后就用了两个for循环一个一个对比,然后逻辑是没问题..但是华丽丽的在验证的过程中超时了….o(╯□╰)o
所以就证明了:在写代码的过程中,只会傻瓜解法的真的就是傻瓜…
于是就百度了一下(嗯对就是酱紫毕竟我写不出来能通过第23个测试的代码我也没办法吖= =)
然后发现正确的答案大家用的都是Map函数来做的,由于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++) {
// 如果没有对应的key添加进去
if (map.containsKey(nums[i])) {
// 原来保存的值对应的下标,它一定小于现在的下标
int value = map.get(nums[i]);
if (i - value <= k) {
return true;
}
}
map.put(nums[i], i);
}
return false;
}
}