Problem
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.
1 | Example 1: |
Solution
Analysis
给定一个数组以及一个整数k, 在数组中查找是否存在两个相等的数组nums[i]和nums[j],而且i和j之间的绝对值差小于等于k.
最简单的方法是使用一个hash表记录数值和下标之间的映射关系, 记录时在遍历数组时同步记录,不用单独出来一个步骤,和two sum问题类似. 当出现重复数字时,判断是否满足条件, 如果不满足,更新hash表元素的下标, 当遍历完数组之后,还没有出现满足条件的情况,返回false.
Code
1 | class Solution { |