标签:
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.
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; } }
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:
Hide Tags
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; } }
169. Majority Element && 229. Majority Element II
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5702180.html