算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 存在重复元素 II,我们先来看题面:
https://leetcode-cn.com/problems/contains-duplicate-ii/
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的 绝对值 至多为 k。
示例
示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:
输入: nums = [1,0,1,1], k = 1
输出: true
示例 3:
输入: nums = [1,2,3,1,2,3], k = 2
输出: false
解题
利用HashMap数据结构,每次存入数值钱先看一下有没有这个数了,如果已经有了,那么看一下这两个数的索引下标之差是不是小于等于k的,如果是的话那么久说明找到了,返回true,如果没有找到就返回false。
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> hm = new HashMap<>();
for(int i=0;i<nums.length;i++){
if(hm.containsKey(nums[i])){
int sub = i - hm.get(nums[i]);
if(sub <= k)
return true;
else
hm.put(nums[i],i);
}
else
hm.put(nums[i],i);
}
return false;
}
}
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文: