标签:duplicate integer array leetcode 重复元素
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 Solution {
public boolean containsNearbyDuplicate1(int[] nums, int k) {
int i = 0, j = 0;
if (nums == null || nums.length < 2)
return false;
while (i < nums.length) {
j = 0;
while (j < k && i + j + 1 < nums.length) {
if (nums[i] == nums[i + j + 1]) {
return true;
}
j++;
}
i++;
}
return false;
}
}
算法二:(Accepted)
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
int i = 0;
if (nums == null || nums.length < 2 || k < 1)
return false;
Map<Integer, Integer> current = new HashMap<Integer, Integer>();
while (i < nums.length) {
if (current.containsKey(nums[i])) {
return true;
} else {
current.put(nums[i], i);
if(i >= k)
current.remove(nums[i-k]);
}
i++;
}
return false;
}
}
T(n) = O(n)
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class SolutionTest {
private Solution s = new Solution();
@Test
public void test(){
int [] nums = {11,22,33,44,55,1,2,3,4,5,6,7,8,1};
int k = 8;
assertEquals(true,s.containsNearbyDuplicate(nums, k));
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
【LeetCode】Contains Duplicate II
标签:duplicate integer array leetcode 重复元素
原文地址:http://blog.csdn.net/baidu_22502417/article/details/46908523