這是小川的第419次更新,第452篇原創(chuàng)
看題和準(zhǔn)備
今天介紹的是LeetCode算法題中Easy級(jí)別的第269題(順位題號(hào)是1207)。給定一個(gè)整數(shù)數(shù)組arr,當(dāng)且僅當(dāng)該數(shù)組中每個(gè)元素的出現(xiàn)次數(shù)唯一時(shí),返回true。
例如:
輸入:arr = [1,2,2,1,1,3]
輸出:true
說(shuō)明:值1出現(xiàn)3次,值2出現(xiàn)2次,值3出現(xiàn)1次。沒(méi)有兩個(gè)值出現(xiàn)的次數(shù)相同。
輸入:arr = [1,2]
輸出:false
輸入:arr = [-3,0,1,-3,1,1,1,-3,10,0]
輸出:true
限制條件:
- 1 <= arr.length <= 1000
- -1000 <= arr[i] <= 1000
第一種解法
題目的意思是判斷數(shù)組中的元素的出現(xiàn)次數(shù)是否唯一,我們可以直接使用HashMap和HashSet結(jié)合,先遍歷arr中的元素,將元素值作為key,出現(xiàn)次數(shù)作為value存入HashMap中,再遍歷HashMap的所有value,存入HashSet中,如果當(dāng)前value已經(jīng)存在,直接返回false。
public boolean uniqueOccurrences(int[] arr) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : arr) {
map.put(num, map.getOrDefault(num, 0)+1);
}
Set<Integer> set = new HashSet<Integer>();
for (Integer count : map.values()) {
if (set.contains(count)) {
return false;
}
set.add(count);
}
return true;
}
第二種解法
使用int數(shù)組計(jì)數(shù)。因?yàn)轭}目限定了原始數(shù)組的長(zhǎng)度和元素值范圍,所以我們可以借助計(jì)數(shù)來(lái)解決此問(wèn)題。
第一次計(jì)數(shù),聲明一個(gè)長(zhǎng)度為2001的int數(shù)組count,將原始數(shù)組的值加上1000后作為新數(shù)組索引。第二次計(jì)數(shù),同樣聲明一個(gè)長(zhǎng)度為2001的int數(shù)組count2,如果count中的當(dāng)前元素不等于0,就將當(dāng)前元素作為count2數(shù)組的索引,元素值累加,加完后判斷元素值是否大于等于2,如果大于,直接返回false。
public boolean uniqueOccurrences2(int[] arr) {
int[] count = new int[2001];
for (int num : arr) {
count[num+1000]++;
}
int[] count2 = new int[2001];
for (int con : count) {
if (con != 0) {
count2[con]++;
if (count2[con] >= 2) {
return false;
}
}
}
return true;
}
第三種解法
和上面第二種解法類(lèi)似,只是將第二步計(jì)數(shù)的int數(shù)組換成了boolean類(lèi)型,其他思路不變。
public boolean uniqueOccurrences3(int[] arr) {
int[] count = new int[2001];
for (int num : arr) {
count[num+1000]++;
}
boolean[] flag = new boolean[2001];
for (int con : count) {
if (con > 0) {
if (flag[con]) {
return false;
} else {
flag[con] = true;
}
}
}
return true;
}
小結(jié)
算法專(zhuān)題目前已更新LeetCode算法題文章275+篇,公眾號(hào)對(duì)話(huà)框回復(fù)【數(shù)據(jù)結(jié)構(gòu)與算法】、【算法】、【數(shù)據(jù)結(jié)構(gòu)】中的任一關(guān)鍵詞,獲取系列文章合集。
以上就是全部?jī)?nèi)容,如果大家有什么好的解法思路、建議或者其他問(wèn)題,可以下方留言交流,點(diǎn)贊、留言、在看就是對(duì)我最大的回報(bào)和支持!