Advertisement
exmkg

2-1

Jan 14th, 2025
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. class Solution {
  2.     public int majorityElement(int[] nums) {
  3.         Map<Integer, Integer> freq = new HashMap<>();
  4.         for (int x : nums) {
  5.             freq.put(x, freq.getOrDefault(x, 0) + 1);
  6.         }
  7.         for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
  8.             if (entry.getValue() > nums.length / 2) {
  9.                 return entry.getKey();
  10.             }
  11.         }
  12.         return Integer.MIN_VALUE;
  13.     }
  14. }
  15.  
  16.  
  17.  
  18. class Solution {
  19.     public int majorityElement(int[] nums) {
  20.         int count = 0;
  21.         int candidate = -1;
  22.         for (int num : nums) {
  23.             // If count of the current candidate number became 0,
  24.             // pick a new candidate number.
  25.             if (count == 0) candidate = num;
  26.            
  27.             // If current number is the candidate number,
  28.             // increase count by 1.
  29.             if (num == candidate) count++;
  30.             // Otherwise, decrement count by 1. You can think
  31.             // of it like "a single non-candidate number kills a single candidate number".
  32.             else count--;
  33.         }
  34.         // Since there is one number that appears > n/2 times, it is un-killable.
  35.         // Hence, it should win over all other candidates.
  36.         return candidate;
  37.     }
  38. }
  39.  
  40.  
  41.  
  42. class Solution {
  43.     public int majorityElement(int[] nums) {
  44.         Arrays.sort(nums);
  45.         int n = nums.length;
  46.         return nums[n / 2];
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement