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.
Public classSolution { PublicList<integer> Majorityelement (int[] nums) { /*first, it can be concluded through analysis that the number of CNT that satisfies the condition is up to 2. Proof: Ifcnt>2⇒cntx (⌊n/3⌋+1) >n exceeds the size of the original array. Then, using the idea of finding more than half of the number of occurrences in an array: 1). First scan, set two counter and variable record array nums[] The highest number of occurrences. 2). The second scan calculates the number of occurrences of two numbers. 3). Determine if the two numbers meet the requirements, then deposit the result set. It is important to note that the order of the first for loop is determined first to determine whether it is equal to M or n*/List<Integer> res=NewArraylist<integer>(); if(nums==NULL|| nums.length<=0)returnRes; intM=0; intN=0; intCountm=0; intCountn=0; for(inti=0;i<nums.length;i++){ /*if (m==nums[i]) countm++; else if (n==nums[i]) countn++; else if (countm==0) {countm=1; M=nums[i]; }else if (countn==0) {countn=1;n=nums[i]; }else {countm--; countn--; }*/ if(m==nums[i]| | Countm==0) {Countm++; m=Nums[i]; }Else if(n==nums[i]| | Countn==0) {Countn++; n=Nums[i]; }Else{Countm--;countn--; }} Countm=0; COUNTN=0; for(inti=0;i<nums.length;i++){ if(nums[i]==m) countm++; Else if(nums[i]==n) countn++; } if(COUNTM>NUMS.LENGTH/3) Res.add (m); if(COUNTN>NUMS.LENGTH/3) Res.add (n); returnRes; }}
[Leedcode 229] Majority Element II