Given an integer array of size n, find all elements this appear more than times ? n/3 ? . The algorithm should run in linear time and in O (1) space.
Hint:
- How many majority elements could it possibly?
Thought analysis: This is an extension of the majority element, which can also be solved by the Moore voting method. First, you need to analyze if such an element (elements that appear more than
? n/3 ? Times) exists, then there must be no more than two, proving that it is easy to understand with contradiction. The next step is to figure out the possible two elements. Two steps can be found to find two candidate and verify that the number of occurrences of candidate exceeds
? n/3 ?Times . The method for finding two candidate candidate is the Moore voting method, similar to the majority element. The reason for verification is that, unlike the majority element, which has already limited the existence of the main element, there is no need for such an element to exist, even if there is a number of uncertainties, so the validation process is required. Time complexity O (n), Spatial complexity O (1).AC Code:
public class Solution {public list<integer> majorityelement (int[] nums) {//moore voting//0632 int candidate1 = 0, Candidate2 = 0, times1 = 0, Times2 = 0; int n = nums.length; for (int i = 0; i < n; i++) {if (nums[i] = = candidate1) {times1++; } else if (nums[i] = = Candidate2) {times2++; } else if (times1 = = 0) {candidate1 = nums[i]; Times1 = 1; } else if (Times2 = = 0) {candidate2 = nums[i]; Times2 = 1; } else{times1--;times2--; }} times1 = 0; Times2 = 0; for (int i = 0; i < n; i++) {if (nums[i] = = candidate1) times1++; else if (nums[i] = = Candidate2) times2++; } list<integer> res = new arraylist<integer> (); if (Times1 > N/3) {res.add (candidate1); } if (tImes2 > N/3) {res.add (CANDIDATE2); } return res; 0649}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode Majority Element II