Contains Duplicate II
https://leetcode.com/problems/contains-duplicate-ii/description/
Given an array of integers and an integerk, find out whether there are two distinct indicesiandjin the array such thatnums[i] = nums[j]and theabsolutedifference betweeniandjis at mostk.
Thoughts
问两个坑是否装同一个数,且坑的indexの差小于k. 遍历,如果当前元素在map中则计算它和当前index的差。map更新为当前的i, 因为要求找最近的,当后面还出现该元素时和i的diff肯定比和i之前的diff小。
Code
Analysis
时间空间都是O(n).
Last updated
Was this helpful?