169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
Hide Tags
Array Divide and Conquer Bit Manipulation
Hide Similar Problems
More readings: https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
public class Solution { public int majorityElement(int[] num) { int major = num[0]; int count = 1; //The majority number has enough counts to cover all other numbers for (int i = 1; i < num.length; ++i) { if (count == 0) { ++count; major = num[i]; } else if (major == num[i]) { ++count; } else --count; } return major; } }
229. Majority Element II
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:
- How many majority elements could it possibly have?
- Do you have a better hint? Suggest it!
Hide Tags
Hide Similar Problems
public class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> results = new ArrayList<>(); if (nums == null || nums.length == 0) return results; int n1 = nums[0]; int n2 = nums[0]; int count1 = 0; //count keeps a "relative" count of current number int count2 = 0; int len = nums.length; for (int i = 0; i < len; ++i) { if (nums[i] == n1) ++count1; else if (nums[i] == n2) ++count2; else if (count1 == 0) { n1 = nums[i]; count1 = 1; } else if (count2 == 0) { n2 = nums[i]; count2 = 1; } else { //Zeros were check beforehand to make sure counts won‘t go negative --count1; --count2; } } count1 = 0; count2 = 0; for (int i = 0; i < len; i++) { if (nums[i] == n1) ++count1; else if (nums[i] == n2) ++count2; } if (count1 > len / 3) results.add(n1); if (count2 > len / 3) results.add(n2); return results; } }
时间: 2024-12-28 04:06:20