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 ...
随机推荐
- python3图片裁剪+转换pdf+压缩
本地大量长图,要发送给别人,所以要对图片进行裁剪+转换pdf+压缩 import zipfile import os from concurrent.futures import ThreadPool ...
- C#实现数字字符串左补齐0的3种方法
int n = 3; string s = n.ToString().PadLeft(4, '0'); //0003 s = string.Format("{0:d4}", n); ...
- 解决“未启用当前数据库的 SQL Server Service Broker,因此查询通知不受支持。如果希望使用通知,请为此数据库启用 Service Broker”错误
转自:http://blog.csdn.net/andrew_wx/article/details/6947317 解决办法: ALTER DATABASE 数据库名称 SET NEW_BROKER ...
- Phonegap在ios7上系统状态栏的问题解决
用Phonegap+jqm开发的应用,在ios6下没问题,但是在ios7下会出现如下系统状态栏和header重合的问题,搜索了一下,发现这其实是 phonegap当前版本的一个已知问题,通过修改./p ...
- HackerRank "AND xor OR"
Actually I think problem statement is somewhat misleading. No need to mention range [L, R] at all. T ...
- objective-c 下面int 和 NSData数据 互相转换的方法
抄自这里 ; NSData *data = [NSData dataWithBytes: &i length: sizeof(i)]; int i; [data getBytes: & ...
- 转:Java学习路线图,专为新手定制的Java学习计划建议
转自:http://blog.csdn.net/jinxfei/article/details/5545874 怎么学习Java,这是很多新手经常会问我的问题,现在我简单描述下一个Java初学者到就业 ...
- 利用mtd工具实现嵌入式设备在线升级
版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] 主要思路是:通过web post方式将升级文件交给CGI程序处理,然后通过mtd工具实现设备在线升级. 1.页面部分 & ...
- Grid_Oracle Grid Infrastructure概念介绍(概念)
2014-03-09 Created By BaoXinjian Thanks and Regards
- angular.js 的angular.copy 、 angular.extend 、 angular.merge
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...