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.
題目要求:輸入一個整數(shù)數(shù)組叁执,查看數(shù)組中是否存在重復(fù)的值誊辉。
使用java中的數(shù)據(jù)結(jié)構(gòu)將已經(jīng)遍歷起來的值存儲起來宇驾,然后查詢當(dāng)前的值是否已經(jīng)遍歷過涮阔。
這里我們使用set叮盘,如果包含重復(fù)值可以檢測出。
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ù)組贩猎,不同的是熊户,要求兩個重復(fù)值的之間的間隔不得超過k
通過hashmap存儲已經(jīng)遍歷過的選項(xiàng)以及最近一次遍歷到時的下標(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ǔ)上重新定義了相同的條件嚷堡,也就是如果兩個值之間的絕對差不超過t,那么就可以稱這兩個值相同艇棕。
要求判斷之前是否存在差值小于t的數(shù)字蝌戒,我們需要知道在當(dāng)前數(shù)字x兩邊的數(shù)字,即最大的小于x的數(shù)字和最小的大于x的數(shù)字沼琉。二叉搜索樹有也有這樣的性質(zhì)北苟,它的左子樹的最右節(jié)點(diǎn)是最大的較小值,右子樹的最左節(jié)點(diǎn)是最小的較大值打瘪。這里我們用TreeSet這個類友鼻,它實(shí)現(xiàn)了紅黑樹,并有集合的性質(zhì)闺骚,非常適合這題彩扔。我們同樣也是維護(hù)一個大小為k的TreeSet,多余k個元素時把最早加入的給刪除僻爽。用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;
}
}
這一題參考了下面的連接