1368. 相同数字

描述

给一个数组,如果数组中存在相同数字,且相同数字的距离小于给定值k,输出YES,否则输出NO

  • 输入的数组长度为n,保证n <= 100000
  • 数组元素的值为x0 <= x <= 1e9
  • 输入的k满足 1 <= k < n
您在真实的面试中是否遇到过这个题?  

样例

给出 array = [1,2,3,1,5,9,3], k = 4, 返回 "YES"

解释:
index为3的1和index为0的1距离为3,满足题意输出YES。

给出 array =[1,2,3,5,7,1,5,1,3], k = 4, 返回 "YES"

解释:
index为7的1和index为5的1距离为2,满足题意。

用哈希表比较容易

class Solution {
public:
    /**
     * @param nums: the arrays
     * @param k: the distance of the same number
     * @return: the ans of this question
     */
    string sameNumber(vector &nums, int k) {
        // Write your code here
        unordered_map mmap;
        for(int i=0;i

你可能感兴趣的:(刷题)