您的位置:首页 > 大数据 > 人工智能

<LeetCode OJ> 219. Contains Duplicate II

2016-01-09 22:49 519 查看


219. Contains Duplicate II

My Submissions

Question

Total Accepted: 40529 Total
Submissions: 142658 Difficulty: Easy

有一个数组和一个整数,如果数组中两个相同的元素(分别在数组中i和j的位置),如果判断是否|i-j|<=k,若是则返回真
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 difference between i and jis at most k.

Subscribe to see which companies asked this question

Hide Tags
Array Hash
Table

Hide Similar Problems
(E) Contains Duplicate (M)
Contains Duplicate III

//思路首先:哈希map(不要用红黑树map)
//遍历数组,首先看当前元素是否在map中,如不在则压入,若在看是否其对应下标和当前下标相距为k
//如果不则将原元素修改为现在的下标
class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(nums.empty())
            return false;
        unordered_map<int,int> umapping;
        umapping[nums[0]]=0;
        for(int i=1;i<nums.size();i++)
        {
            //if(umapping.count(nums[i]) == 0)//没有出现(统计函数)
            if(umapping.find(nums[i]) == umapping.end())//直接查找
                umapping[nums[i]]=i;
            else if((i-umapping[nums[i]])<=k)//相距小于k
                return true;
            else
                umapping[nums[i]]=i;
        }
        return false;
    }
};


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50490187

原作者博客:http://blog.csdn.net/ebowtang
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: