Contains Duplicate II
来源:互联网 发布:金十数据看白银 编辑:程序博客网 时间:2024/06/06 04:56
题目地址: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.
与Contains Duplicate 类似,用HashMap就能解决这个问题,无非是这次要存储元素的位置信息了。
步骤如下:
- 如果一个元素在map中不存在,那么推进去;
- 如果存在,那么比较一下当前元素与以前元素的位置差有多少,小于等于k,返回true,否则继续循环,注意:这里要更新该元素的在map中的位置信息了,因为前面的位置已经超过k了,但是不等于后面就再没有这样的元素了,比如{1,0,1,1}与1。
代码实现如下:
public class ContainsDuplicateII { public static boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i])){ if (i - map.get(nums[i]) <= k) return true; else { map.put(nums[i], i); continue; } }else { map.put(nums[i], i); } } return false; } public static void main(String[] args) { int[] a = {1,0,1,1}; int k = 1; System.out.println(containsNearbyDuplicate(a, k)); }}
0 0
- Contains Duplicate && Contains Duplicate II
- [LeetCode]Contains Duplicate II
- Contains Duplicate II
- [LeetCode] Contains Duplicate II
- leetcode Contains Duplicate II
- LeetCode Contains Duplicate II
- [leetcode] Contains Duplicate II
- LeetCode Contains Duplicate II
- LeetCode219:Contains Duplicate II
- #219 Contains Duplicate II
- 219. Contains Duplicate II
- 【leetcode】Contains Duplicate II
- leetcode--Contains Duplicate II
- 219Contains Duplicate II
- Contains Duplicate II
- Contains Duplicate II
- Contains Duplicate II
- Leetcode_219 Contains Duplicate II
- 网站流量统计指标
- Android 面试笔试集锦 --- 基本知识点 整理版
- malloc,free使用入门
- linux.1:创建分区和文件系统
- TextSeekBar 文字跟随拖快移动
- Contains Duplicate II
- 简述SQL Server Replication的常见错误及其处理
- 前端面试题
- JVM JRE JDK
- 启动 Eclipse 弹出“Failed to load the JNI shared library jvm.dll”错误的解决方法!
- webstrom破解教程
- 物化视图
- 基于SOA 的软件过程管理在中小企业中的应用
- 使用java代码在jsp中显示实体数据