LeetCode 229. Majority Element II
原题链接在这里:https://leetcode.com/problems/majority-element-ii/
题目:
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋
times.
Note: The algorithm should run in linear time and in O(1) space.
Example 1:
Input: [3,2,3] Output: [3]
Example 2:
Input: [1,1,1,3,3,2,2,2] Output: [1,2]
题解:
因为个数超过n/3的值最多有两个, 现在改成维护两个candidate.
最后再扫一遍数组,查看这两个最常出现值的实际出现次数,看看是否大于n/3, 大于的都加入返回res中.
Note: two candidate can't be equal, thus before adding candidate2, need to check if it is equal to candidate1, if yes, then skip. e.g.[1, 1, 1]. If both can1 and can2 are initialized as 1, then result would be [1, 1]. But the result should be [1].
Time Complexity: O(n). n = nums.length.
Space O(1).
AC Java:
1 class Solution { 2 public List<Integer> majorityElement(int[] nums) { 3 List<Integer> res = new ArrayList<Integer>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 8 //最多有两个数字大于n/3 9 int major1 = 1; 10 int major2 = 2; 11 int count1 = 0; 12 int count2 = 0; 13 for(int i = 0; i<nums.length; i++){ 14 if(nums[i] == major1){ 15 count1++; 16 }else if(nums[i] == major2){ 17 count2++; 18 }else if(count1 == 0){ 19 major1 = nums[i]; 20 count1 = 1; 21 }else if(count2 == 0){ 22 major2 = nums[i]; 23 count2 = 1; 24 }else{ 25 count1--; 26 count2--; 27 } 28 } 29 30 count1 = 0; 31 count2 = 0; 32 for(int num : nums){ 33 if(num == major1){ 34 count1++; 35 } 36 if(num == major2){ 37 count2++; 38 } 39 } 40 41 if(count1 > nums.length/3){ 42 res.add(major1); 43 } 44 if(count2 > nums.length/3){ 45 res.add(major2); 46 } 47 return res; 48 } 49 }
AC C++:
1 class Solution { 2 public: 3 vector<int> majorityElement(vector<int>& nums) { 4 vector<int> res; 5 int can1 = 1; 6 int can2 = 2; 7 int count1 = 0; 8 int count2 = 0; 9 for(int& num : nums){ 10 if(num == can1){ 11 count1++; 12 }else if(num == can2){ 13 count2++; 14 }else if(count1 == 0){ 15 can1 = num; 16 count1 = 1; 17 }else if(count2 == 0){ 18 can2 = num; 19 count2 = 1; 20 }else{ 21 count1--; 22 count2--; 23 } 24 } 25 26 count1 = 0; 27 count2 = 0; 28 for(int& num : nums){ 29 if(num == can1){ 30 count1++; 31 }else if(num == can2){ 32 count2++; 33 } 34 } 35 36 if(count1 > nums.size()/3){ 37 res.push_back(can1); 38 } 39 40 if(count2 > nums.size()/3){ 41 res.push_back(can2); 42 } 43 44 return res; 45 } 46 };