Contains Duplicate I
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
題目要求:輸入一個(gè)整數(shù)數(shù)組,查看數(shù)組中是否存在重復(fù)的值。
使用java中的數(shù)據(jù)結(jié)構(gòu)將已經(jīng)遍歷起來的值存儲(chǔ)起來,然后查詢當(dāng)前的值是否已經(jīng)遍歷過。
這里我們使用set,如果包含重復(fù)值可以檢測(cè)出。
class Solution {
public boolean containsDuplicate(int[] nums) {
HashSet<Integer> set=new HashSet<>();
if (nums==null||nums.length==0)
return false;
for (int i=0;i<nums.length;i++){
if (!set.add(nums[i]))
return true;
}
return false;
}
}
Contains DuplicateII
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 absolute difference between i and j is at most k.
題目要求:同I,同樣是整數(shù)數(shù)組,不同的是,要求兩個(gè)重復(fù)值的之間的間隔不得超過k
通過hashmap存儲(chǔ)已經(jīng)遍歷過的選項(xiàng)以及最近一次遍歷到時(shí)的下標(biāo)值。如果重復(fù)數(shù)值的下標(biāo)之間的值不超過k,那么就證明重復(fù)值滿足條件
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums.length<=1)
return false;
HashSet<Integer> set=new HashSet<>();
for (int i=0;i<nums.length;i++){
if (i>k)
set.remove(nums[i-k-1]);
if (!set.add(nums[i]))
return true;
}
return false;
}
}
Contains Duplicate III
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
題目要求:在II的基礎(chǔ)上重新定義了相同的條件,也就是如果兩個(gè)值之間的絕對(duì)差不超過t,那么就可以稱這兩個(gè)值相同。
要求判斷之前是否存在差值小于t的數(shù)字,我們需要知道在當(dāng)前數(shù)字x兩邊的數(shù)字,即最大的小于x的數(shù)字和最小的大于x的數(shù)字。二叉搜索樹有也有這樣的性質(zhì),它的左子樹的最右節(jié)點(diǎn)是最大的較小值,右子樹的最左節(jié)點(diǎn)是最小的較大值。這里我們用TreeSet這個(gè)類,它實(shí)現(xiàn)了紅黑樹,并有集合的性質(zhì),非常適合這題。我們同樣也是維護(hù)一個(gè)大小為k的TreeSet,多余k個(gè)元素時(shí)把最早加入的給刪除。用ceiling()和floor()可以找到最小的較大值和最大的較小值。
class Solution {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
TreeSet<Integer> set=new TreeSet<>();
for(int i=0;i<nums.length;i++){
int temp=nums[i];
if(set.ceiling(temp)!=null&&set.ceiling(temp)<=t+temp)return true;
if(set.floor(temp)!=null&&temp<=t+set.floor(temp))return true;
set.add(temp);
if(set.size()>k)set.remove(nums[i-k]);
}
return false;
}
}
這一題參考了下面的連接