LeetCode 219. Contains Duplicate II
来源:互联网 发布:天谕动漫人物捏脸数据 编辑:程序博客网 时间:2024/06/07 19:45
问题描述:
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。
代码实现:
public boolean containsNearbyDuplicate(int[] nums, int k) { if (nums == null || nums.length <= 1) { return false; } Map<Integer, Integer> keyLocationsMap = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (keyLocationsMap.get(nums[i]) != null) { if ((i - keyLocationsMap.get(nums[i])) <= k) { return true; } } keyLocationsMap.put(nums[i], i); } return false; }
问题改进:
在上面解法中,使用了一个hashmap来存放一个数的值和下标,当值相等是,然后比较下标。如果下标超过了需要等下下标。可以使用一个hashSet,值存放当前下标之前的k个数,之前的数全部删除。
代码实现:
public boolean containsNearbyDuplicate(int[] nums, int k) { Set<Integer> containsSet = new HashSet<Integer>(k ); for (int i = 0; i < nums.length; i++) { if (i > k) {//k+1的时候删除0. containsSet.remove(nums[i - k - 1]); } if (!containsSet.add(nums[i])) { return true; } } return false; }
总结
将一个问题限定在一定的范围内,设定边界是一种很好的方法。
阅读全文
0 0
- [leetcode] 219. Contains Duplicate II
- LeetCode 219. Contains Duplicate II
- LeetCode:219. Contains Duplicate II
- 【Leetcode】219. Contains Duplicate II
- Leetcode 219. Contains Duplicate II
- 219. Contains Duplicate II LeetCode
- 【LeetCode】219. Contains Duplicate II
- Leetcode 219. Contains Duplicate II
- LeetCode *** 219. Contains Duplicate II
- LeetCode 219. Contains Duplicate II
- LeetCode 219. Contains Duplicate II
- LeetCode 219. Contains Duplicate II
- leetcode 219. Contains Duplicate II
- 219.[Leetcode]Contains Duplicate II
- Leetcode 219. Contains Duplicate II
- 【leetcode】219. Contains Duplicate II
- LeetCode - 219. Contains Duplicate II
- leetcode 219. Contains Duplicate II
- 【PAT】【Advanced Level】1087. All Roads Lead to Rome (30)
- 08:判断一个数能否同时被3和5整除
- Android7.0 PowerManagerService(1) 启动过程
- (源码分析)Android系统时间-自动获取
- Eigen介绍及简单使用
- LeetCode 219. Contains Duplicate II
- ubuntu16.04QT5.8安装和arm环境下的qte-5.8.0安装配置
- mysql字符串截取
- ELECTRICAL TYPE
- nginx配置本地虚拟域名
- react-native 代码编程规范、约定
- android监听通话时长只针对在APP中拨打电话
- Java基础核心知识总结(绝对经典)
- csdn 请选择文章类型 解决办法