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<int> &nums, int k) {
        // Write your code here
        unordered_map<int,int> mmap;
        for(int i=0;i<nums.size();i++){
            if(mmap.find(nums[i])!=mmap.end()&&i-mmap[nums[i]]<k) return "YES";
            mmap[nums[i]]=i;
        }
        return "NO";
    }
};

猜你喜欢

转载自blog.csdn.net/vestlee/article/details/80717517