LeetCode :Contains Duplicate II

来源:互联网 发布:淘宝会员名是什么 编辑:程序博客网 时间:2024/06/04 08:06

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.

中文:给出一个整数数组,判断该数组内是否有两个元素值是相同的,且他们的索引值相差不大于k,是则返回true,否则返回false

class Solution {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        unordered_map<int, int> m;        for (int i = 0; i < nums.size(); ++i) {            if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k) return true;            else m[nums[i]] = i;        }        return false;    }};
1 0
原创粉丝点击