Leetcode题解 219. Contains Duplicate II
来源:互联网 发布:ubuntu15.10安装mysql 编辑:程序博客网 时间:2024/06/06 04:21
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 不能重复获取hashMap.get(nums[i]) 容易超时
解法一
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { if (nums.length <= 1) { return false; } HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (hashMap.containsKey(nums[i]) && i - hashMap.get(nums[i]) <= k) { return true; } hashMap.put(nums[i], i); } return false; }}
解法二:
public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { if(nums==null || nums.length<2) return false; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i=0; i<nums.length; i++) { Integer num=map.get(nums[i]); if(num!=null) { int j = num; if(i-j<=k) return true; map.put(nums[i],i); } else { map.put(nums[i], i); } } return false; }}
0 0
- leetcode题解-217. Contains Duplicate&&219.Contains Duplicate II
- Leetcode题解 219. Contains Duplicate II
- LeetCode题解:Contains Duplicate II
- LeetCode 题解(196) : Contains Duplicate II
- 【leetcode题解】【99.38】【E】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. 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
- javascript之获取对象几种方式比较
- 虚函数HOOK
- 通过i++,所理解到的技术感悟
- MySQL查询昨天、今天、7天、近30天、本月、上月 数据
- 计算机图形学专业术语
- Leetcode题解 219. Contains Duplicate II
- Android之自定义view-加载效果
- http抓包(PC\移动)
- 今天总结
- 图的最短路径(dijkstra算法/floyd算法)
- 图解用Scientific Toolworks Understand分析Microsoft DirectX SDK (June 2010)自带D3D示例
- 24点游戏及其算法
- 三次握手和四次挥手
- 简单的猜拳游戏 却有不简单的算法