超时版:

/*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. mysql将字符转换成数字

    在操作mysql时,经常需要将字符转换成数字,这一步虽然简单,但不常用的话也很容易忘记,现将在网上找到的方法记录如下: 1.将字符的数字转成数字,比如'0'转成0可以直接用加法来实现例如:将pony表 ...

  2. FileMode文件模式

    一.FileMode.Append Append追加: 如果文件存在,则打开文件,把指针指到文件的末尾:如果不存在,则新建文件 二.FileMode.Create Create:新建 如果文件存在,则 ...

  3. js中数组Array的一些常用方法总结

    var list = new Array()是我们在js中常常写到的代码,今天就总结一下Array的对象具有哪些方法. list[0] = 0; list[1] = 1; list[2] = 2; 或 ...

  4. C#接口作用的深入理解

    1.C#接口的作用 C#接口是一个让很多初学C#者容易迷糊的东西,用起来好像很简单,定义接口,里面包含方法,但没有方法具体实现的代码,然后在继承该接口的类里面要实现接口的所有方法的代码,但没有真正认识 ...

  5. 【linux】/etc/fstab修复

    /etc/fstab在修改后,如果配置错误直接重启的话会导致系统崩溃.建议大家重启前执行mount -a ,mount -a是自动挂载 /etc/fstab 里面的东西.若不慎重启了,会出现开机错误, ...

  6. 剑指offer系列20--从上到下打印二叉树

    * 20 [题目]从上往下打印出二叉树的每个节点,同层节点从左至右打印. * [思路]从根结点开始,先保存结点,再看根结点的左右结点有没有值. * 有,就将左右值放到集合中: * 根节点输出后,打印根 ...

  7. 【并发编程】Executor类的继承结构

    来自为知笔记(Wiz)

  8. IDrac的console无法键盘输入

    IDrac的console无法键盘输入问题? 解:disable IE 的protect 功能 (Idrac的正常工作需要先安装Java,同时IDrac只支持IE和Firefox.) 方法: IE-& ...

  9. 实现web数据同步的四种方式

    http://www.admin10000.com/document/6067.html 实现web数据同步的四种方式 1.nfs实现web数据共享 2.rsync +inotify实现web数据同步 ...

  10. android中的数据库操作

    如何在android中调用数据库资源 在android中主要有两种方法来实现对数据库的访问,一种是adb shell方式,另一种是通过相关的android 的java类来间接的对数据库来进行操作.其中 ...