leetcode 219. Contains Duplicate II

来源:互联网 发布:淘宝客服售前必备技巧 编辑:程序博客网 时间:2024/06/10 23:15

前言

非常简单但非常有灵性的一道题目,同时考察数据结构和贪婪算法,贪婪算法的巧妙使用是解决本题的一个亮点。

题目描述

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。
很显然的一个解法,用一个map来保存出现过的数,key是值,value为下标。如果重复,就判断间隔是否小于等于k,但是容易忽视一种情况,如果重复数字出现了多次,而满足条件的间隔出现在数组后面的位置,这时候如何更新保存在map中的下标成为一个问题。稍作思考就发现本题贪婪算法完全适用,再次出现的重复数字直接进行更新下标的操作,因为若前面的重复数字不满足间隔k的要求,那么就意味着可能满足的i和j只可能出现在后方位置,因此贪心策略就允许我们覆盖前面位置的i,直到循环结束。代码实现如下:

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