Leeetcode 217
import java.util.HashSet;
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> map=new HashSet<>();
for(int num:nums)
{
if(map.contains(num))
{
return true;
}else
{
map.add(num);
}
}
return false;
}
}
Leetcode 219
import java.util.HashMap;
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++)
{
if(map.containsKey(nums[i]))
{
if(i-map.get(nums[i])<=k) return true;
}
map.put(nums[i],i);
}
return false;
}
}
Leetcode 220
两层for循环
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
long[] longnum=new long[nums.length];
for(int i=0;i<nums.length;i++)
{
longnum[i]=nums[i];
}
for(int i=1;i<longnum.length;i++)
{
for(int j=Math.max(0,i-k);j<i;j++)
{
if(Math.abs(longnum[i]-longnum[j])<=t)return true;
}
}
return false;
}
平衡二叉树
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Long> tree=new TreeSet<>();
long[] longnum=new long[nums.length];
for(int i=0;i<nums.length;i++)
{
longnum[i]=nums[i];
}
for(int i=0;i<longnum.length;i++)
{
Long temp = tree.ceiling(longnum[i]);
if(temp!=null&&Math.abs(longnum[i]-temp)<=t) return true;
temp=tree.floor(longnum[i]);
if(temp!=null&&Math.abs(longnum[i]-temp)<=t) return true;
tree.add(longnum[i]);
//维护滑动窗口
if(tree.size()>k) tree.remove(longnum[i-k]);
}
return false;
}