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.
算法思想
- 思想一:
两个数组下标i,j,在叫j-i<=k的范围内扫描判断,直到查找到两个相等的元素nums[i]=nums[j],但问题虽然未提到算法时间的要求,但却不允许这一算法的通过,这个算法的复杂度为(KN)。
- 思想二:
一个数组下标i, 使用hashmap记录扫描过得所有数字,利用hashmap.containsKey方法判断当前扫描数是否有和已经扫描过得数相同,如果有并且相差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));
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-09 20:17:02