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 ...
随机推荐
- TKinter事件及绑定
Windows编程是基于消息的,绝大多数界面编程是基于事件的. 事件的绑定函数bind: 语法 :窗体对象.bind(事件类型,回调函数) 所谓的"回调函数",就是这个函数我们不用 ...
- 数字根(digital root)
来源:LeetCode 258 Add Dights Question:Given a non-negative integer num , repeatedly add all its digi ...
- ajax简单案例:字符串返回类型
小知识点: implode("^",$v) 拼数组为字符串, split/explode("|") 拆字符串为数组; "你好"-> ...
- 导出resource文件的的资源
写个小工具,方便一次性将resource文件中的资源导出,不然反编译后一个个找,真是太麻烦了. using System;using System.Collections.Generic;using ...
- Asp.Net MVC 路由 - Asp.Net 编程 - 张子阳
http://cache.baiducontent.com/c?m=9d78d513d98316fa03acd2294d01d6165909c7256b96c4523f8a9c12d522195646 ...
- DB2 组内分组排序,游标使用
CREATE PROCEDURE Sys_Init_tblaccountsuser_sortid () P1: BEGIN '; ; ; ; DECLARE CUR1 CURSOR WITH RETU ...
- jquery radio的取值 radio的选中 radio的重置
radio 按钮组, name=”sex”. <input type="radio" name="sex" value="Male"& ...
- Microsoft SQL Server Management Studio 导出触发器脚本
- 加了GO后报 'GO' 附近有语法错误
单独运行SQL无问题,了加GO就报错. 是你的SQL语句中,有些行的结尾处只有Char(13)没有Char(10),即:只有回车符没有换行符,这种状态在视觉上是没办法区分的. 参考:http://ww ...
- json换行符的处理
JS端的: var s = JSON.stringify(str); var ss = s.replace(/\\n/g, "\\n") .replace(/\\'/g, &quo ...