從一個數組中尋找出現奇數次的數字


 

 假設給定了數組nums為[0,1,2,3,4,5,6,7,8,9,10,10,9,8,7,6,5,4,1,2,3,3,0]

其中3出現了3次

而其他數字都出現了兩次

則我們應該得到結果為3

第一種方式:使用Hash

 1     /**
 2      * 使用hash
 3      * */
 4     public static int singleNumber_1(int[] nums) {
 5         Map<Integer, Integer> map = new HashMap<>();
 6         for(Integer num : nums) {
 7             /*
 8              *  1.remove與put操作相對耗費時間
 9              *  
10              *     if(map.containsKey(num)) {
11              *        map.remove(num);
12              *    }else {
13              *        map.put(num, 0);
14              *    }
15              * **/
16             if(map.get(num) != null) {
17                 map.put(num, map.get(num)+1);
18             }else {
19                 map.put(num, 1);
20             }
21         }
22         int result = -1;
23         for(Integer key : map.keySet()) {
24             if(map.get(key)%2 != 0) {
25                 result = key;
26             }
27                 
28         }
29         return result;
30     }
View Code

第二種方式:使用^

 1     /**
 2      * 異或
 3      * a^b^c^b^a = (a^a)(b^b)^c = 0^c = c
 4      * */
 5     public static int singleNumber_2(int [] nums) {
 6         int ans = nums[0];
 7         if (nums.length > 1) {
 8            for (int i = 1; i < nums.length; i++) {
 9               System.out.println(ans + "^" + nums[i] + ":");
10               ans = ans ^ nums[i];
11               System.out.println(ans);
12            }
13          }
14          return ans;
15     }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM