您的位置:首页 > 大数据 > 人工智能

LeetCode:219. Contains Duplicate II

2016-01-10 10:52 555 查看
Given an array of integers and an integer k,
find out whether there are two distinct indices i and j in
the array such that nums[i] = nums[j] and
the difference between i and jis
at most k.

查找数组中的是否有重复元素,并且要求查找半径小于等于k的值,设定两个指针就好,start 和end,具体实现看代码:

import java.util.HashSet;
import java.util.Set;

/**
* Created by jason on 2016/1/10.
*/
class Solution39 {
Set<Integer> apperNum = new HashSet<Integer>();
public boolean containsNearbyDuplicate(int[] nums, int k) {
int start=0,end =0;
if (nums == null || nums.length <0) {return false;}
for (int i=0; i<nums.length; i++) {
if(!apperNum.contains(nums[i])) {
apperNum.add(nums[i]);
end++;
}else {
return true;
}
if (end - start > k) {
apperNum.remove(nums[start]);
start++;
}
}
return false;
}
}
public class LC39 {
public static void main(String[] ars) {
Solution39 solution39 = new Solution39();
int[] nums = new int[]{2, 3, 2, 5};
if (solution39.containsNearbyDuplicate(nums, 1)) {
System.out.println("true");
}else {
System.out.println("false");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: