超时版:

/*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;
} }
}

  

最新文章

  1. NodeJS 最快速搭建一个HttpServer
  2. lufylegend游戏引擎
  3. Django 源码小剖: Django ORM 查询管理器
  4. 后缀数组:SPOJ SUBST1 - New Distinct Substrings
  5. SQL Server 数据的创建、增长、收缩
  6. Linux中的cron计划任务配置方法(详细)
  7. ABP中动态WebAPI原理解析
  8. 页面loading提示效果
  9. 【转载】makefile经典教程
  10. 五年 Web 开发者 star 的 github 整理说明
  11. Javascript里的if判断与逻辑运算符(||, &amp;&amp;)和比较运算符的特别之处
  12. [国嵌攻略][103][Linux内核模块基础]
  13. Android OpenGL ES 开发(八): OpenGL ES 着色器语言GLSL
  14. 【UOJ UNR #1】争夺圣杯
  15. 【一天一道LeetCode】#61. Rotate List
  16. 学习熟悉箭头函数, 类, 模板字面量, let和const声明
  17. python全栈开发day53-mysql
  18. 解决ant Design dva ajax跨越请求 (status=0)
  19. ThunderBird对只有回复地址的邮件过滤
  20. 20165315 2017-2018-2《Java程序设计》课程总结

热门文章

  1. 转:java日志组件介绍(common-logging,log4j,slf4j,logback )
  2. NET 2.0 OCR文字识别技术(Tesseract 引擎)[转]
  3. SharePoint 2010 最佳实践学习总结------第1章 SharePoint Foundation开发基础
  4. web前端基础知识及快速入门指南
  5. bzoj4716 假摔
  6. libcurl上传文件,添加自定义头
  7. linux内核模块相关命令:lsmod,depmod,modprobe,modinfo,insmod,rmmod 使用说明
  8. ubuntu ipv6网络电视(avplay)
  9. activiti自定义流程之整合(二):使用angular js整合ueditor创建表单
  10. JavaScript中对于闭包的理解