亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用大小為 30K 的數組進行測試時,使用 HashMap 實現的代碼失敗

使用大小為 30K 的數組進行測試時,使用 HashMap 實現的代碼失敗

慕森王 2023-07-19 17:07:14
我正在努力解決下面鏈接中的代碼挑戰,但在第 13 到 19 種情況下失敗了。我讀到 HashMap 可以獲取大量數據,但我的解決方案似乎不適用于數組(雜志)為30K。以下是我實施的解決方案。我用 4K 數組測試了代碼,效果很好static void checkMagazine(String[] magazine, String[] note) {? ? int initSize_m = (int) Math.ceil(magazine.length / 0.75);? ? int initSize_n = (int) Math.ceil(note.length / 0.75);? ? HashMap<Integer, String> m_hash= new HashMap<Integer, String>(initSize_m);? ? HashMap<Integer, String> n_hash= new HashMap<Integer, String>(initSize_n);? ? for(int i= 0; i < note.length; i++){? ? ? n_hash.put(i, note[i]);? ? }? ? for(int i= 0; i < magazine.length; i++){? ? ? m_hash.put(i, magazine[i]);? ? }? ? boolean flag=true;? ? if(note.length<magazine.length){? ? for (Map.Entry<Integer, String> entry : n_hash.entrySet()) {? ? ? ? flag = m_hash.containsValue(entry.getValue());? ? ? ? if(flag){? ? ? ? ? ? m_hash.values().removeIf(v -> v.equals(entry.getValue()));? ? ? ? }else{? ? ? ? ? ? break;? ? ? ? }? ? }? ? }else{? ? for (Map.Entry<Integer, String> entry : m_hash.entrySet()) {? ? ? ? flag = n_hash.containsValue(entry.getValue());? ? ? ? if(flag){? ? ? ? ? ? n_hash.values().removeIf(v -> v.equals(entry.getValue()));? ? ? ? }else{? ? ? ? ? ? break;? ? ? ? }? ? }? ? }? ? if(flag){? ? ? ? System.out.println("Yes");? ? }else{? ? ? ? System.out.print("No");? ? }}案例13至19失敗
查看完整描述

1 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

您的地圖應該將單詞作為鍵,將它們的計數作為值。按單詞在輸入中的位置映射單詞并不能幫助您找到它們。


Mapa (也稱為)的全部要點Dictionary是能夠通過給定鍵快速查找值。在這種情況下,HashMap操作是 O(1),而通過迭代所有條目值(如您的情況)來查找值要慢得多 -> O(n)。我強烈建議您閱讀有關地圖和集合的內容。


這是一個正確的解決方案:


public class HackerRank {

    public static void main(String[] args) {

        final Scanner in = new Scanner(System.in);


        final int numberOfWordsInMagazine = in.nextInt();

        final int numberOfWordsInNote = in.nextInt();


        final Map<String, Integer> wordsInMagazine = new HashMap<>();

        for (int i = 0; i < numberOfWordsInMagazine; i++) {

            final String word = in.next();

            wordsInMagazine.merge(word, 1, Integer::sum);

        }



        boolean canPrintMessage = true;

        for (int i = 0; i < numberOfWordsInNote; i++) {

            final String word = in.next();


            Integer remainingCount = wordsInMagazine.computeIfPresent(word, (key, value) -> value - 1);

            if (null == remainingCount || remainingCount < 0) {

                canPrintMessage = false;

                break;

            }

        }


        System.out.println(canPrintMessage ? "Yes" : "No");

    }

}


查看完整回答
反對 回復 2023-07-19
  • 1 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號