229. Majority Element II

来源:互联网 发布:pdf电子书 知乎 编辑:程序博客网 时间:2024/06/07 02:11

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

Hint:

  1. How many majority elements could it possibly have?
摘自:
https://leetcode.com/discuss/43175/c-solution-with-explanation-o-n-time-and-o-1-space

We can apply the same idea as easy version of majority element. If we remove three elements with different value at the same time, finally we should filter out the majority elements. So in the first pass, we search for possible majority elements (the number of majority element <3), and then for each candidate, we scan the array again to confirm wether it's majority or not.

public static List<Integer> majorityElement(int[] nums){if (nums == null || nums.length == 0)return new ArrayList<Integer>();List<Integer> result = new ArrayList<Integer>();int number1 = nums[0], number2 = nums[0], count1 = 0, count2 = 0, len = nums.length;for (int i = 0; i < len; i++){if (nums[i] == number1)count1++;else if (nums[i] == number2)count2++;else if (count1 == 0){number1 = nums[i];count1 = 1;} else if (count2 == 0){number2 = nums[i];count2 = 1;} else{count1--;count2--;}}count1 = 0;count2 = 0;for (int i = 0; i < len; i++){if (nums[i] == number1)count1++;else if (nums[i] == number2)count2++;}if (count1 > len / 3)result.add(number1);if (count2 > len / 3)result.add(number2);return result;}


0 0