219Contains Duplicate II
来源:互联网 发布:手机语音拨号软件 编辑:程序博客网 时间:2024/06/04 19:02
题目链接:https://leetcode.com/problems/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.
解题思路:
- 数据结构 HashMap, key 为元素值,value 为该元素的数组下标。
- 如果哈希表中没有该元素,就把元素及其下标 put 到哈希表中。
- 如果哈希表中已有该元素,获得 HashMap 中该元素之前的下标,如果当前下标与哈希表中的下标的差 小于等于 k,返回 true。否则,将当前下标放入 map 中,替换之前的下标。
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { if(nums == null || nums.length == 0) return false; HashMap<Integer, Integer> map = new HashMap(); int len = nums.length; for(int i = 0; i < len; i ++) { if(map.containsKey(nums[i])) { int pre = map.get(nums[i]); if(i - pre <= k) return true; else map.put(nums[i], i); } else map.put(nums[i], i); } return false; }}
19 / 19 test cases passed.Status: AcceptedRuntime: 452 ms
0 0
- #219 Contains Duplicate II
- 219Contains Duplicate II
- 219Contains Duplicate II
- 219Contains Duplicate II
- 219Contains Duplicate II
- 219 Contains Duplicate II
- [219] Contains Duplicate II
- 219Contains Duplicate II
- leetcode 219: Contains Duplicate II
- LeetCode 219:Contains Duplicate II
- Contains Duplicate II - LeetCode 219
- Leetcode[219]-Contains Duplicate II
- LeetCode 219 Contains Duplicate II
- Leetcode 219 Contains Duplicate II
- 【Leetcode】Contains Duplicate II #219
- Leetcode 219 Contains Duplicate II
- leetcode 219:Contains Duplicate II
- LeetCode 219: Contains Duplicate II
- run ceph in docker
- MUI 的学习与使用
- Unity3D-重新编译Mono加密DLL
- java Collections.sort()实现List排序的默认方法和自定义方法
- 后缀自动机小结 (spoj 8222)
- 219Contains Duplicate II
- Testlink和mantis整合
- Autolayout下设置多个View等比例排列
- TCP流量控制与拥塞控制
- 【干货】产品经理每日必看的数据统计表
- 整理整理生产者消费者模式,用通俗的话描述
- 这些技术都是我们技术人绕不过去的坎
- OC内存管理之—自动释放池
- IOS去除文件后缀名