LeetCode 219.Contains Duplicate II
Description:
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.
Example 1:
Input: [1,2,3,1,2,3,4], k = 3
Output: True
Example 2:
Input: [1,2,3,1,2,3,4], k = 2
Output: False
分析:
首先,最简单的当然是两层循环,但肯定是超时的。
换一种思路,解决这种题目,经常会用到STL中的集合set;
在这道题中,我们可以把数组一个个放到集合s中去,利用集合元素不会重复的特性,可判断出已经出现的数字,也即是出现重复的数,此时再去循环判断两个重复数的位置与k的关系,小于等于k即为真。
代码中我们用了一个currentSize来记录当前集合s的大小,若外循环尝试插入一个数时s的大小不变,体现在代码中就是s.size() == currentSize,说明此时出现重复的数,内循环再判断之前出现该数的位置,两者相减后比较与k的关系,得出结果。
代码如下:
运行超时版本:
1 | class Solution { |
AC版本:
1 |
|