Find the element with highest occurrences in an array [java]

后端 未结 11 1498
后悔当初
后悔当初 2021-01-18 02:36

I have to find the element with highest occurrences in a double array. I did it like this:

int max = 0;
for (int i = 0; i < array.length; i++) {
       in         


        
相关标签:
11条回答
  • 2021-01-18 03:14

    Here's a java solution --

            List<Integer> list = Arrays.asList(1, 2, 2, 3, 2, 1, 3);
            Set<Integer> set = new HashSet(list);
            int max = 0;
            int maxtemp;
            int currentNum = 0;
            for (Integer k : set) {
                maxtemp = Math.max(Collections.frequency(list, k), max);
                currentNum = maxtemp != max ? k : currentNum;
                max = maxtemp;
            }
            System.out.println("Number :: " + currentNum + " Occurs :: " + max + " times");
    
    0 讨论(0)
  • 2021-01-18 03:14

    You can solve this problem in one loop with without using HashMap or any other data structure in O(1) space complexity.

    Initialize two variables count = 0 and max = 0 (or Integer.MIN_VALUE if you have negative numbers in your array)

    The idea is you will scan through the array and check the current number,

    • if it is less than your current max...then do nothing
    • if it is equal to your max ...then increment the count variable
    • if it is greater than your max..then update max to current number and set count to 1

    Code:

    int max = 0, count = 0;
    for (int i = 0; i < array.length; i++) {
        int num = array[i];
        if (num == max) {
            count++;
        } else if (num > max) {
            max = num;
            count = 1;
        }
    }
    
    0 讨论(0)
  • 2021-01-18 03:19

    Use Collections.frequency option:

     List<String> list = Arrays.asList("1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8");
          int max = 0;
          int curr = 0;
          String currKey =  null;
          Set<String> unique = new HashSet<String>(list);
    
              for (String key : unique) {
                    curr = Collections.frequency(list, key);
    
                   if(max < curr){
                     max = curr;
                     currKey = key;
                    }
                }
    
              System.out.println("The number "  + currKey + " happens " + max + " times");
    

    Output:

    The number 12 happens 10 times

    0 讨论(0)
  • 2021-01-18 03:21

    This is how i have implemented in java..

    import java.io.*;
    class Prog8
    {
        public static void main(String[] args) throws IOException 
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Input Array Size:");
            int size=Integer.parseInt(br.readLine());
            int[] arr= new int[size];
            System.out.println("Input Elements in Array:");
            for(int i=0;i<size;i++)
                arr[i]=Integer.parseInt(br.readLine());
            int max = 0,pos=0,count = 0;
            for (int i = 0; i < arr.length; i++)
            {
                count=0;
                for (int j = 0; j < arr.length; j++) 
                {
                    if (arr[i]==arr[j])
                        count++;
                }
                if (count >=max)
                {
                    max = count;
                    pos=i;
                }
            }
    
            if(max==1)
                System.out.println("No Duplicate Element.");
            else
                System.out.println("Element:"+arr[pos]+" Occourance:"+max);
        }
    }
    
    0 讨论(0)
  • 2021-01-18 03:27

    The solution with Java 8

           int result = Arrays.stream(array)
               .boxed()
               .collect(Collectors.groupingBy(i->i,Collectors.counting()))
               .values()
               .stream()
               .max(Comparator.comparingLong(i->i))
               .orElseThrow(RuntimeException::new));
    
    0 讨论(0)
  • 2021-01-18 03:27

    Here is Ruby SOlution:

    def maxOccurence(arr)
      m_hash = arr.group_by(&:itself).transform_values(&:count)
      elem = 0, elem_count = 0
      m_hash.each do |k, v|
        if v > elem_count
            elem = k
            elem_count = v
        end
      end
      "#{elem} occured #{elem_count} times"
    end
    
    p maxOccurence(["1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8"])
    

    output:

    "12 occured 10 times"
    
    0 讨论(0)
提交回复
热议问题