oj219. Contains Duplicate II
来源:互联网 发布:unity3d行走播放动画 编辑:程序博客网 时间:2024/06/16 17:06
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,找出数组中是否有两个不同的索引i和j,使得nums [i] = nums [j],i和j之间的绝对差值最多为k。
注意:英语不好,我一开始一直理解错误,认为只要出现不满足条件的情况就返回false,但是看答案才知道,只要有满足条件的情况就返回ture。全不满足才返回false。
自己思路(超时):
通过新建list来逐个存取数组,每次存新元素时如果list中已有重复元素,就拿出最靠后的重复元素下标,判断差值是否小于等于k。但是查找的时候应该会很费时。
public boolean containsNearbyDuplicate(int[] nums, int k) { if(nums.length ==0) return false; List<Integer> l = new ArrayList<Integer>(); for(int i =0;i<nums.length;i++){ if(l.lastIndexOf(nums[i]) != -1){ int j = l.lastIndexOf(nums[i]); if(i-j <= k) { return true; }else{ l.add(nums[i]); } } else{ l.add(nums[i]); } } return false; }答案思路:
用hashMap存值和下标,出现相同元素就判断差值是否小于等于k,满足条件就返回true,否则put该元素,这里重复元素下标会替换已有元素的下标。节省空间和查找时间。
public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer,Integer> m = new HashMap<Integer,Integer>(); for(int i =0;i<nums.length;i++){ if(m.containsKey(nums[i])){ if(i - m.get(nums[i]) <=k){ return true; } } m.put(nums[i],i); } return false; }
0 0
- oj219. Contains Duplicate II
- 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
- gulp入门指导
- 数据库事务及其四大特性
- Spring Boot系列之八 多数据源配置整体介绍
- XRecyclerView的Header包含ListView冲突解决(XRecyclerView嵌套ListView)
- MRT(MODIS reprojection tools)下载及安装
- oj219. Contains Duplicate II
- Qt数据库之数据库常用操作
- 电脑系统崩溃如何找回桌面文件?简单,有效!
- 24点游戏
- C# List 排序
- 锋利的jQuery总结(二)
- logstash kafka output 日志处理
- 多项式求和 HDU
- Linux下生成patch和打patch