Contains DuplicateII
超时版:
/*Contains Duplicate II
Given an array of integers and an integer k, find out whether there 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.
*/ public class Leetcode2 { public static void main(String[] args) {
int arr[]= {1,2,34,43,1};
System.out.println(containsNearbyDuplicate(arr,1)); // TODO Auto-generated method stub } public static boolean containsNearbyDuplicate(int[] nums, int k) { for (int i = 0; i < nums.length - 1; i++) {
int temp = k + i;
int y = ((temp > nums.length - 1) ? nums.length : temp+1);
for (int j = 1; j < y; j++) {
int x = ((i+j )> nums.length - 1) ? nums.length-1 : (i+j);
if((nums[x] - nums[i])==0)
return true;
}
}
return false;
} /* public static boolean containsNearbyDuplicate(int[] nums, int k) { int x;
for (int i = 0; i < nums.length - 1; i++) {
int temp = k + i; while(temp<=nums.length-1)
{ int temp2=temp;
for(int j=i+1;j<temp2;j++) {
x=nums[j]-nums[i];
if(x==0)
return true;
}
} }
return false;
}
*/ }
AC版:注意集合框架的使用!!
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) { Map<Integer,Integer> tm=new TreeMap<Integer,Integer>(); {
for (int i = 0; i < nums.length ; i++)
{ if(tm.containsKey(nums[i]))
{
int j=tm.get(nums[i]);
if((i-j)<=k)
return true;
}
tm.put(nums[i],i);
}
return false;
} }
}
Contains DuplicateII的更多相关文章
- LeetCode OJ:Contains DuplicateII(是否包含重复II)
Given an array of integers and an integer k, find out whether there are two distinct indices i and j ...
随机推荐
- JS如何调用隐藏按钮的click事件
js如何调用隐藏按钮的click事件:1.设定隐藏不要使用Visiable属性,使用style.display=none:2.触发JS事件可以使用fireEvent方法,如:document.getE ...
- LintCode "Binary Representation"
Not hard to think of a solution. But the key is all details. class Solution { public: /** *@param n: ...
- javascript url 相关函数(escape/encodeURL/encodeURIComponent区别)
JS获取url参数及url编码.解码 完整的URL由这几个部分构成:scheme://host:port/path?query#fragment ,各部分的取法如下: window.location. ...
- linux系统中rsync+inotify实现服务器之间文件实时同步
最近需要对服务器上的文件实施动态备份,我又不想每次都手动来进行备份,在网上找了挺多资料,发现使用rsync就可以实现,如果想要实现实时同步,还可以使用rsync+inotify组合,本文就是以组合方式 ...
- 重复ID的记录,只显示其中1条
--重复ID的记录,只显示其中1条 --生成原始表 select * into #tempTable from ( select '1' as id ,'a' as name union all se ...
- gcc中动态库和静态库的链接顺序
so文件:动态库a文件: 静态库exe文件:可执行程序(linux下以文件属性来标示是否是可执行文件,与后缀名无关) 经过自己写的一些测试程序,大致了解了下gcc中链接顺序问题,总结出以下几点:1,动 ...
- Can not perform this action after onSaveInstanceState
java.lang.RuntimeException: Unable to resume activity {com.tongyan.nanjing.subway/com.tongyan.struct ...
- PC-Lint安装配置与集成到VS2010
第一篇 PC-lint 9 安装及配置教程 1.从这里下载PC-lint.9.0e.rar,解压缩(目录中的patch文件夹不用,因为它只能将PC-lint升级到9.0e ) 2.点击pclint9s ...
- NYOJ16 矩形嵌套(DAG最长路)
矩形嵌套 紫书P262 这是有向无环图DAG(Directed Acyclic Graph)上的动态规划,是DAG最长路问题 [题目链接]NYOJ16-矩形嵌套 [题目类型]DAG上的dp & ...
- poj 3048 Max Factor(素数筛)
这题就是先写个素数筛,存到prime里,之后遍历就好,取余,看是否等于0,如果等于0就更新,感觉自己说的不明白,引用下别人的话吧: 素数打表,找出20000之前的所有素数,存入prime数组,对于每个 ...