leetcode 219

219. Contains Duplicate II

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,找出数组中是否存在两个距离不超过k的相同的数。存在返回true;反之,返回false.

思路:我们首先想到的是将数组中的每个元素与它周围距离在k以内的元素对比,这样算法的时间复杂度为O(n2),算法效率太差。如果用set存放每次需要对比的数,那么每次查找的次数从k减少为logk,这样会大大提高效率。

代码如下:

 1 class Solution {
 2 public:
 3     bool containsNearbyDuplicate(vector<int>& nums, int k) {
 4         set<int> s;
 5         if(k <= 0)
 6         {
 7             return false;
 8         }
 9         if(k >= nums.size())
10         {
11             k = nums.size() - 1;
12         }
13         for( int i = 0; i < nums.size(); i++ )
14         {
15             if( i > k )
16             {
17                 s.erase(nums[i - k - 1]);
18             }
19             if( s.find(nums[i]) != s.end())
20             {
21                 return true;
22             }
23             s.insert(nums[i]);
24         }
25         return false;
26     }
27 };

 

转载于:https://www.cnblogs.com/shellfishsplace/p/6367990.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值