Java 中的眾數元素


假設我們給定一個整數陣列。任務是在給定陣列中找到特定元素的索引。例如:

輸入-1

N = 8
A[ ] = { 1,2,4,3,3,1,1,5}

輸出

1

說明 − 在給定的整數陣列中,出現次數最多的數字是“1”。因此輸出是“1”。

輸入-2

N = 6
A[ ] = {1,5,4,4,1,1}

輸出

1

說明 − 在給定的整數陣列中,出現次數最多的數字是“1”。因此我們可以返回輸出“1”。

解決這個問題的方法

給定的陣列包含多個整數,我們必須在其中找到出現頻率最高的元素。為了線上性時間 O(n) 和線性空間 O(n) 內解決這個問題,我們可以使用雜湊對映的方法。

在這種方法中,我們將建立一個無序對映(STL 庫),它包含鍵值對,其中鍵將是元素,值將是元素的出現次數。在遍歷對映時,我們將找到數字的最大出現次數,並將該數字作為輸出返回。

  • 輸入大小為 N 的陣列

  • 一個整數函式 maxOccurrence(int A[], int size) 接受一個數組及其大小作為輸入,並返回頻率最高的數字。

  • 透過將鍵作為元素,值作為其頻率來建立陣列所有元素的雜湊對映。

  • 遍歷對映並檢查是否有任何元素具有最高頻率,然後將結果作為數字返回。否則,如果陣列中不存在任何數字,則返回“-1”。

示例

import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
class Majority_Element{
   public static int checkMajorityElement(int arr[], int N){
      Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
      for (int i = 0; i < N; i++){
         if (mp.containsKey(arr[i]))
            mp.put(arr[i], mp.get(arr[i]) + 1);
         else
            mp.put(arr[i], 1);
      }
      for (Map.Entry<Integer, Integer> entry : mp.entrySet()){
         if (entry.getValue() > (N / 2))
            return entry.getKey();
      }
      return -1;
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter size of array:");
      int N = 6;
      int arr[] = {2,1,1,2,2,2};
      System.out.println("Enter elements of array:");
      for (int i = 0; i < N; i++)
         arr[i] = sc.nextInt();
      int ans = checkMajorityElement(arr, N);
      if (ans != -1)
         System.out.println("Majority Element is: " + ans);
      else
         System.out.println("No majority element in array");
   }
}

輸出

執行以上程式碼將生成以下輸出:

Enter size of array: 6
Enter elements of array: 2 1 1 2 2 2
Majority Element is: 2

更新於:2021年2月5日

920 次檢視

啟動你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.