Majority Number II

Question

  1. Given an array of integers,
  2. the majority number is the number that occurs more than 1/3 of the size of the array.
  3. Find it.
  4. Example
  5. Given [1, 2, 1, 2, 1, 3, 3], return 1.
  6. Note
  7. There is only one majority number in the array.
  8. Challenge
  9. O(n) time and O(1) extra space.

题解

Majority Number 的升级版,之前那道题是『两两抵消』,这道题自然则需要『三三抵消』,不过『三三抵消』需要注意不少细节,比如两个不同数的添加顺序和添加条件。

C++

  1. class Solution {
  2. public:
  3. /**
  4. * @param nums: A list of integers
  5. * @return: The majority number occurs more than 1/3.
  6. */
  7. int majorityNumber(vector<int> nums) {
  8. if (nums.empty()) return -1;
  9. int k1 = 0, k2 = 0, c1 = 0, c2 = 0;
  10. for (auto n : nums) {
  11. if (!c1 || k1 == n) {
  12. k1 = n;
  13. c1++;
  14. } else if (!c2 || k2 == n) {
  15. k2 = n;
  16. c2++;
  17. } else {
  18. c1--;
  19. c2--;
  20. }
  21. }
  22. c1 = 0;
  23. c2 = 0;
  24. for (auto n : nums) {
  25. if (n == k1) c1++;
  26. if (n == k2) c2++;
  27. }
  28. return c1 > c2 ? k1 : k2;
  29. }
  30. };

Java

  1. public class Solution {
  2. /**
  3. * @param nums: A list of integers
  4. * @return: The majority number that occurs more than 1/3
  5. */
  6. public int majorityNumber(ArrayList<Integer> nums) {
  7. if (nums == null || nums.isEmpty()) return -1;
  8. // pair
  9. int key1 = -1, key2 = -1;
  10. int count1 = 0, count2 = 0;
  11. for (int num : nums) {
  12. if (count1 == 0) {
  13. key1 = num;
  14. count1 = 1;
  15. continue;
  16. } else if (count2 == 0 && key1 != num) {
  17. key2 = num;
  18. count2 = 1;
  19. continue;
  20. }
  21. if (key1 == num) {
  22. count1++;
  23. } else if (key2 == num) {
  24. count2++;
  25. } else {
  26. count1--;
  27. count2--;
  28. }
  29. }
  30. count1 = 0;
  31. count2 = 0;
  32. for (int num : nums) {
  33. if (key1 == num) {
  34. count1++;
  35. } else if (key2 == num) {
  36. count2++;
  37. }
  38. }
  39. return count1 > count2 ? key1 : key2;
  40. }
  41. }

源码分析

首先处理count == 0的情况,这里需要注意的是count2 == 0 && key1 = num, 不重不漏。最后再次遍历原数组也必不可少,因为由于添加顺序的区别,count1 和 count2的大小只具有相对意义,还需要最后再次比较其真实计数器值。

复杂度分析

时间复杂度 O(n), 空间复杂度 O(2 \times 2) = O(1).

Reference