Majority Number II
阿新 • • 發佈:2021-07-18
Source
Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array. Find it. Example Given [1, 2, 1, 2, 1, 3, 3], return 1. Note There is only one majority number in the array. Challenge O(n) time and O(1) extra space.
題解
題Majority Number的升級版,之前那道題是『兩兩抵消』,這道題自然則需要『三三抵消』,不過『三三抵消』需要注意不少細節,比如兩個不同數的新增順序和新增條件。
Java
public class Solution { /** * @param nums: A list of integers * @return: The majority number that occurs more than 1/3 */ public int majorityNumber(ArrayList<Integer> nums) { if (nums == null || nums.isEmpty()) return -1; // pair int key1 = -1, key2 = -1;int count1 = 0, count2 = 0; for (int num : nums) { if (count1 == 0) { key1 = num; count1 = 1; continue; } else if (count2 == 0 && key1 != num) { key2 = num; count2 = 1;continue; } if (key1 == num) { count1++; } else if (key2 == num) { count2++; } else { count1--; count2--; } } count1 = 0; count2 = 0; for (int num : nums) { if (key1 == num) { count1++; } else if (key2 == num) { count2++; } } return count1 > count2 ? key1 : key2; } }
原始碼分析
首先處理count == 0
的情況,這裡需要注意的是count2 == 0 && key1 = num
, 不重不漏。最後再次遍歷原陣列也必不可少,因為由於新增順序的區別,count1 和 count2的大小隻具有相對意義,還需要最後再次比較其真實計數器值。
複雜度分析
時間複雜度 O(n), 空間複雜度 O(2×2)= O(1)O(2×2)=O(1).