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 ...
随机推荐
- Android Camera 相机程序编写
Android Camera 相机程序编写 要自己写一个相机应用直接使用相机硬件,首先应用需要一个权限设置,在AndroidManifest.xml中加上使用设备相机的权限: <uses-per ...
- CentOS 6.0最小化编译安装Nginx+MySQL+PHP+Zend
http://www.osyunwei.com/archives/235.html 引言: 操作系统:CentOS 6.0 32位 下载地址:http://mirrors.163.co ...
- Javascript之类型检测
一.检测原始(基本数据:字符串.数字.布尔.null.undefined)类型. 用typeof检测原始类型:1.对于字符串,typeof返回"string"; 2.对于数字,ty ...
- HackerRank "Playing with numbers"
This is 'Difficult' - I worked out it within 45mins, and unlocked HackerRank Algorithm Level 80 yeah ...
- LeetCode "Minimum Height Tree" !!
Simple data structure but not that easy to figure out.. MHT -> balanced tree.https://leetcode.com ...
- Ansible之playbook
简介 playbook是一个非常简单的配置管理和多主机部署系统.可作为一个适合部署复杂应用程序的基础.playbook可以定制配置,可以按指定的操作步骤有序执行,支持同步和异步方式.playbook是 ...
- Django数据库设计中字段为空的方式
今天在做数据库设计的时候,设计了如下User表,其中我把email和phone字段设置为允许为空: class User(models.Model): username = models.CharFi ...
- CFLAGS,CPPFLAGS,CXXFLAGS in Makefile
CC 与 CXX: 这是 C 与 C++ 编译器命令.默认值一般是 “gcc” 与 “g++”. CPPFLAGS will be given to the C preprocessor ...
- 103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to ...
- eclipse导入html、js、xml报错的问题
今天重新安装eclipse,在导入部分html.js.xml文件,报错,解决办法如下: eclipse->window->preferences->Team,点击validation ...