多數元素


描述: 

給定一個大小為  的數組,找到其中的多數元素。多數元素是指在數組中出現次數大於  ⌊ n/2 ⌋ 的元素。
你可以假設數組是非空的,並且給定的數組總是存在多數元素。

示例 1:

輸入: [3,2,3]

輸出: 3

示例 2:

輸入: [2,2,1,1,1,2,2]

輸出: 2

思路:

這道題有很多種方法求解:

這里提供兩個方法:

    1. 利用散列表,進行計數,即<數字,出現次數>,最后遍歷散列表,找出出現次數大於n/2的元素。
    2. 消除法,每次遇到兩個不同的數字,則將這兩個數字從數組中刪除。這樣最后剩下的元素,一定是出現次數最多的元素。

java(方法一)

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int majorityElement(int[] nums) {
        double n = Math.ceil(nums.length / 2.0);
        Map<Integer, Integer> dict = new HashMap<>(10);
        for (int num : nums) {
            if (dict.get(num) == null) {
                dict.put(num, 1);
            } else {
                dict.put(num, dict.get(num) + 1);
            }
        }
        for (Integer key : dict.keySet()) {
            if (dict.get(key) >= n) {
                return key;
            }
        }
        return -1;
    }
}

結果:

 

 python3(方法二)

class Solution:
      def majorityElement(self, nums: List[int]) -> int:
        flags = [True for num in nums]
        i = 0
        j = i + 1
        while i < len(nums):
            if flags[i]:
                while j < len(nums):
                    if nums[i] != nums[j] and flags[j]:
                        flags[i], flags[j] = False, False
                        break
                    j += 1
            i += 1
        i = 0
        while i < len(nums):
            if flags[i]:
                return nums[i]
            i += 1
        return -1

結果:

 

 

 

 

 


免責聲明!

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



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