簡體   English   中英

給定一個整數數組 arr,編寫一個 function 當且僅當數組中每個值的出現次數唯一時才返回 true

[英]Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique

import java.util.*;
class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        HashMap<Integer,Integer> hash = new HashMap<>();
        for(int i = 0;i<arr.length;i++){
            if(hash.containsKey(arr[i])){
                hash.put(arr[i],hash.get(arr[i])+1);
            }else{
                hash.put(arr[i],1);
            }
        }
        for(int i = 0;i<arr.length;i++){
            for(int j = i+1;j<arr.length-1;j++){
                if(arr[i]!=arr[j] && hash.get(arr[i])==hash.get(arr[j])){
                    return false;
                }
            }
        }
      return true;
    }
}

我的代碼實際上在 1 個測試用例 [1,2] 中失敗。誰能告訴我原因以及如何優化我的代碼

您的代碼輸入 [1,2] 失敗的原因是,您的數組大小為 2 並且根據您的代碼

for(int i = 0;i<arr.length;i++){
        for(int j = i+1;j<arr.length-1;j++){
            if(arr[i]!=arr[j] && hash.get(arr[i])==hash.get(arr[j])){
                return false;
            }
        }
    }

它永遠不會進入第二個 for 循環內(i=0 所以 j=i+1 即 j=1 和 arr size = 2 所以 j<(2-1) 條件對於 i=1 也失敗,j=i+1 即 j =2,j<(2-1) 條件失敗)。

嘗試

for(int i = 0;i<arr.length-1;i++){
        for(int j = i+1;j<arr.length;j++){
            if(arr[i]!=arr[j] && hash.get(arr[i])==hash.get(arr[j])){
                return false;
            }
        }
    }

你讓i從 0(包括)到length (不包括)。 因此,當length為 2 時,即為您提供 0 和 1。

你有ji+1 (incl) 到length-1 (excl)。 這是兩個輸入的空范圍。 i+1至少為 1, length-1也為 1。由於j循環沒有運行,您將找不到任何匹配項。

這會更有意義:

for (int i = 0; i < arr.length - 1; i++) {
    for (int j = i + 1; j < arr.length; j++) {

這實際上會檢查您的陣列中的不同對。

您的代碼的簡化版本:

public static boolean uniqueOccurrences(int... arr) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int value : arr)
        map.merge(value, 1, Integer::sum);
    return map.size() == new HashSet<>(map.values()).size();
}

或者使用流的單個語句:

public static boolean uniqueOccurrences(int... arr) {
    return IntStream.of(arr).boxed()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).values().stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).values().stream()
            .allMatch(i -> i == 1);
}

我會替換那個循環:

for(int i = 0;i<arr.length;i++){
            for(int j = i+1;j<arr.length-1;j++){
                if(arr[i]!=arr[j] && hash.get(arr[i])==hash.get(arr[j])){
                    return false;
                }
            }
        }
      return true;

有了這個,也更簡化了。 因為Set中的每個項目都是唯一的,並且您的密鑰也是唯一的。 如果兩者相等,則存在一對一映射。

Set<Integer> counts = new HashSet<>();
counts.addAll(hash.values());
return counts.size() == hash.keySet().size();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM