超时版:

/*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的更多相关文章

  1. 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 ...

随机推荐

  1. php 同步因子的并发处理

    在php中,如果处理支付时,会涉及到并发. 具体体现在同步通知支付结果和异步通知结果. 拿支付宝来说,同步通知call_back和异步通知notify是没有固定先后顺序的. 有可能notify先通知到 ...

  2. RMAN备份与恢复之删除过期备份

    使用crosscheck backupset或crosscheck backup之后,提示所有备份集都为available状态,当他执行delete obsolete时,提示有两个文件需要删除.实际上 ...

  3. HBase(七): HBase体系结构剖析(下)

    目录: write Compaction splite read Write: 当客户端发起一个Put请求时,首先根据RowKey寻址,从hbase:meta表中查出该Put数据最终需要去的HRegi ...

  4. input绑定datapicker控件后input再绑定blur或者mouseout等问题

    input绑定datapicker控件后input再绑定blur或者mouseout等问题 问题描述:今天在修改一个东西的时候需要给一个input输入域绑定blur事件,从而当它失去焦点后动态修改其中 ...

  5. openssl与cryptoAPI交互AES加密解密

    继上次只有CryptoAPI的加密后,这次要实现openssl的了 动机:利用CryptoAPI制作windows的IE,火狐和chrome加密控件后,这次得加上与android的加密信息交互 先前有 ...

  6. .NET RSACryptoServiceProvider PEM + DER Support

    http://www.christian-etter.de/?p=771 In .NET, RSACryptoServiceProvider greatly simplifies common tas ...

  7. OC—设计模式-通知的使用

    通知 通知(广播) 可以一对多的发送通知(一个发送者 多个观察者) 特别注意:在发送者 发送通知的时候,必须有观察者 发送者,就是注册一个通知中心,以他为中心,发送消息 通过通知的名字,来判断是哪个通 ...

  8. 发送WIN+SAPCE键,WINDOWS,空格键

    键盘代码部份转自:http://www.cnblogs.com/cpcpc/archive/2011/02/22/2123055.html 由于喜欢用CTRL+空格键切换输入法,在WIN8上有所不习惯 ...

  9. Web通过JS调用客户端

    代码实现==> <html> <head> <script language="javascript"> function Run(str ...

  10. TSP(旅行者问题)——动态规划详解(转)

    1.问题定义 TSP问题(旅行商问题)是指旅行家要旅行n个城市,要求各个城市经历且仅经历一次然后回到出发城市,并要求所走的路程最短. 假设现在有四个城市,0,1,2,3,他们之间的代价如图一,可以存成 ...