• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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 difference between i and j is at most k.

 Better idea is to maintain a hashset that contains at most k numbers

 1 public class Solution {
 2     public boolean containsNearbyDuplicate(int[] nums, int k) {
 3         Set<Integer> set = new HashSet<Integer>();
 4         for(int i = 0; i < nums.length; i++){
 5             if(set.contains(nums[i])) return true;
 6             set.add(nums[i]);
 7             if(set.size()>k) set.remove(nums[i-k]);
 8         }
 9         return false;
10     }
11 }

 

posted @ 2015-12-17 07:44  neverlandly  阅读(198)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3