码迷,mamicode.com
首页 > 其他好文 > 详细

【一天一道LeetCode】#219. Contains Duplicate II

时间:2016-07-29 15:39:12      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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 j is at most k.

(二)解题

题目大意:给定一个数组,如果数组中存在连个相等的数之间的距离小于k,则返回true,反之返回false。
解题思路:只需要找到距离小于K的两个相等的数,很容易想到采用hash表的算法。
定义一个hashmap,hashmap[i]表示i这个数最近出现的位置。
当遍历到下一个i出现时,计算i-hashmap[i],如果小于k则代表存在,反之则不存在。
具体解释看代码:

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        unordered_map<int,int>  hash;//STL中的hashmap为unordered_map
        int size = nums.size();
        for(int i = 0 ; i < size ; i++){
            if(hash.find(nums[i])!=hash.end()){//如果之前出现过nums[i]这个数,就计算距离
                if(i - hash[nums[i]]<=k) return true;
            }
            hash[nums[i]] = i;//保存最近出现nums[i]的位置
        }
        return false;
    }
};

【一天一道LeetCode】#219. Contains Duplicate II

标签:

原文地址:http://blog.csdn.net/terence1212/article/details/52063035

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!