編程之美 - 1.5 快速找出故障機器__編程

來源:互聯網
上載者:User
問題導讀:


給你一副雜亂的撲克牌(不包括大小王),任意從其中抽出一張牌,怎樣用最簡單的方法來知道抽出的是1~13中的那一張。(不要求知道花色)

註:類似題目


解決方案:


package Chapter1;import java.util.HashMap;import java.util.Map;import java.util.Map.Entry;public class Func_1_5 {    /*    給你一副雜亂的撲克牌(不包括大小王),任意從其中抽出一張牌,怎樣用最簡單的方法來知道抽出的是1~13中的那一張。(不要求知道花色)     */    int func1(int []arr, int flag) {        // 利用 map,統計每張撲克牌出現的次數,最後找出次數為3的撲克牌        Map<Integer, Integer> map = new HashMap<>();        for (int a : arr) {            if (map.containsKey(a)) {                map.put(a, map.get(a) + 1);            } else {                map.put(a, 1);            }        }        for (Entry<Integer, Integer> e : map.entrySet()) {            if (e.getValue() == flag) return e.getKey();        }        return 0;    }    Map<Integer, Integer> func2(int []arr, int flag) {        // 不儲存滿狀態的元素        Map<Integer, Integer> map = new HashMap<>();        for (int a : arr) {            if (map.containsKey(a)) {                map.put(a, map.get(a) + 1);                if (map.get(a) == flag) {                    map.remove(a); // 滿狀態,直接刪除                }            } else {                map.put(a, 1);            }        }        return map;    }    int func3(int []arr) {        int res = 0;        // 自異或 為 0        // 和0異或 為 本身        for (int a : arr) {            res ^= a;        }        return res;    }    int func4(int []arr, int total) {        // 原始和 - 剩餘和        int sum = 0;        for (int a : arr) {            sum += a;        }        return total - sum;    }    public static void main(String []args) {        Func_1_5 f = new Func_1_5();        int []arr = new int[13*4 -1];        for (int i = 1; i <= arr.length; i++) {            arr[i-1] = i%13 == 0 ? 13 : i%13;        }        int res_1 = f.func1(arr, 3);        System.out.println("res_1 : " + res_1);        Map<Integer, Integer> map = f.func2(arr, 4);        for(Entry<Integer, Integer> e : map.entrySet()) {            System.out.println("res_2 : " + e.getKey());        }        int res_3 = f.func3(arr);        System.out.println("res_3 : " + res_3);        int res_4 = f.func4(arr, 13 * 7 * 4);        System.out.println("res_4 : " + res_4);    }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.