Given an integer array of size n, find all elements that appear more than
Note: The algorithm should run in linear time and in O(1) space.
Example 1:
⌊ 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]
import java.util.*;
public class NewClass7 {
HashMap<Integer,Integer> ar=new HashMap<Integer,Integer>();
public void majorityElement(int[] nums) {
for(int i=0;i<nums.length;i++)
{
if(ar.containsKey(nums[i]))
{
ar.put(nums[i],ar.get(nums[i])+1);
}else
{
ar.put(nums[i],1);
}
}
for(int i:ar.keySet())
{
if(ar.get(i)>nums.length/3)
{
System.out.print(i+" ");
}
}
}
public static void main(String args[])
{
int ar[]={1,1,1,3,3,2,2,2};
NewClass7 ob=new NewClass7();
ob.majorityElement(ar);
}
}
No comments:
Post a Comment