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.
Problem Solving Ideas:
"The beauty of programming" looking for the original title of the Water king, two traversal, a traversal to find the number of possible occurrences more than NUMS.LENGTH/3, (three times different number is discarded), the second verification can be.
The Java implementation is as follows:
Public list<integer> majorityelement (int[] nums) { list<integer> List = new Arraylist<integer> () if (nums = = NULL | | nums.length = = 0) return List;int left = nums[0], right=nums[0];int count1 = 1, Count2 = 0;for (int i = 1; i < nums.length; i++) {if (nums[i] = = left) count1++;else if (right==left) {right=nums[i];count2=1;} else if (Right==nums[i]) Count2++;else if (count1==0) {left=nums[i];count1=1;} else if (count2==0) {right=nums[i];count2=1;} else{count2--;count1--;}} count1=0;count2=0;for (int i=0;i<nums.length;i++) {if (nums[i]==left) Count1++;else if (nums[i]==right) count2++;} if (COUNT1>NUMS.LENGTH/3) List.add (left), if (COUNT2>NUMS.LENGTH/3) List.add (right), return list; }
Java for Leetcode 229 Majority Element II