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 ...
随机推荐
- android 旋转手机的时候,如何忽略onCreate再次被系统调用?
实现一个程序,主要是不想在手机横竖屏的时候重新onCreate,所以在配置文件中增加了配置选项: android:configChanges="orientation|keyboardHid ...
- eclipse svn subclipse下载地址
http://subclipse.tigris.org/servlets/ProjectDocumentList?folderID=2240 Eclipse 3.x Subclipse release ...
- oracle11g服务项及其启动顺序
oracle安装完成后共七个服务,含义分别为: 1. Oracle ORCL VSS Writer Service:Oracle卷映射拷贝写入服务,VSS(Volume Shadow Copy Ser ...
- Android Intent 用法全面总结
[代码全屏查看]-Android Intent 用法全面总结 // [1].[代码] 调用拨号程序 跳至 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] / ...
- mysql frm的恢复,data里只有frm文件的恢复
mysql frm的恢复,data里只有frm文件的恢复 mysql frm的恢复,data里只有frm文件的恢复,换了系统,装了windows2003,重装最新5.4版的mysql,把原来的一个数据 ...
- 【jmeter】测试报告优化<二>
如果按JMeter默认设置,生成报告如下: 从上图可以看出,结果信息比较简单,对于运行成功的case,还可以将就用着.但对于跑失败的case,就只有一行assert错误信息.(信息量太少了,比较难找到 ...
- C\C++拾遗------C#程序员重温C\C++之要点
1.开发工具:建议采用VS2012及2013 1).因为VS2012对C++编码实现了自动编排格式(Ctrl E D) 2).提供智能感知(联想输入)功能 相比VS2010及以前版本对于习惯了智能感知 ...
- css样式单位取整,去掉'px'
alert(parseInt($(".themes1").css("margin-left"), 10));
- ajaxForm笔记
<script src="Scripts/jquery.form.js" type="text/javascript"></script> ...
- linux挂载文件
Linux挂载Winodws共享文件夹 mount -t cifs -o username=***,password=*** //192.168.1.48/share /mnt 其中-t表示要挂载的类 ...