1. 程式人生 > >169-求眾數

169-求眾數

數組 shm 其中 輸入 contains 一個 輸出 ont i++

給定一個大小為 n 的數組,找到其中的眾數。眾數是指在數組中出現次數大於 ⌊ n/2 ⌋ 的元素。
你可以假設數組是非空的,並且給定的數組總是存在眾數。
示例 1:
輸入: [3,2,3]
輸出: 3

示例 2:
輸入: [2,2,1,1,1,2,2]
輸出: 2


解法1:
public static int majorityElement(int[] nums) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int a:nums)
        {
            map.put(a,map.containsKey(a)
?map.get(a)+1:1); } int n=nums.length; int temp=0; for (int i=0;i<nums.length;i++) { if (map.get(nums[i])>n/2) { temp=nums[i]; break; } } return temp; } 解法2:
public static int majorityElement(int[] nums) { int count=1; for (int i=1;i<nums.length;i++) { if (nums[0]==nums[i]) { count++; }else { count--; } if (count<0) { count=1; nums[
0]=nums[i]; } } return nums[0]; }

169-求眾數