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

后端 未结 11 1499
后悔当初
后悔当初 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:35

    Update:

    • As Maxim pointed out, using HashMap would be a more appropriate choice than Hashtable here.
    • The assumption here is that you are not concerned with concurrency. If synchronized access is needed, use ConcurrentHashMap instead.

    You can use a HashMap to count the occurrences of each unique element in your double array, and that would:

    • Run in linear O(n) time, and
    • Require O(n) space

    Psuedo code would be something like this:

    • Iterate through all of the elements of your array once: O(n)
      • For each element visited, check to see if its key already exists in the HashMap: O(1), amortized
      • If it does not (first time seeing this element), then add it to your HashMap as [key: this element, value: 1]. O(1)
      • If it does exist, then increment the value corresponding to the key by 1. O(1), amortized
    • Having finished building your HashMap, iterate through the map and find the key with the highest associated value - and that's the element with the highest occurrence. O(n)

    A partial code solution to give you an idea how to use HashMap:

    import java.util.HashMap;
    ...
    
        HashMap hm = new HashMap();
        for (int i = 0; i < array.length; i++) {
            Double key = new Double(array[i]);
            if ( hm.containsKey(key) ) {
                value = hm.get(key);
                hm.put(key, value + 1);
            } else {
                hm.put(key, 1);
            }
        }
    

    I'll leave as an exercise for how to iterate through the HashMap afterwards to find the key with the highest value; but if you get stuck, just add another comment and I'll get you more hints =)

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

    I will suggest another method. I don't know if this would work faster or not.

    Quick sort the array. Use the built in Arrays.sort() method.

    Now compare the adjacent elements. Consider this example:

    1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4 9 9 9 10 10 10 29 29 29 29 29 29

    When the adjacent elements are not equal, you can stop counting that element.

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

    Solution 1: Using HashMap

    class test1 {
        public static void main(String[] args) {
    
        int[] a = {1,1,2,1,5,6,6,6,8,5,9,7,1};
        // max occurences of an array
        Map<Integer,Integer> map = new HashMap<>();
          int max = 0 ; int chh = 0 ;
          for(int i = 0 ; i < a.length;i++) {
              int ch = a[i];
              map.put(ch, map.getOrDefault(ch, 0) +1);
          }//for
          Set<Entry<Integer,Integer>> entrySet =map.entrySet();
    
          for(Entry<Integer,Integer> entry : entrySet) {
              if(entry.getValue() > max) {max = entry.getValue();chh = entry.getKey();}
    
          }//for
        System.out.println("max element => " + chh);
        System.out.println("frequency => " + max);
        }//amin
    }
    /*output =>
    max element => 1
    frequency => 4
    
    */
    

    Solution 2 : Using count array

    public class test2 {
        public static void main(String[] args) {
             int[] a = {1,1,2,1,5,6,6,6,6,6,8,5,9,7,1};
        int max = 0 ; int chh = 0;
        int count[] = new int[a.length];
        for(int i = 0 ; i <a.length ; i++) {
            int ch = a[i];
            count[ch] +=1 ;
        }//for
    
        for(int i = 0 ; i <a.length ;i++)  {
            int ch = a[i];
            if(count[ch] > max) {max = count[ch] ; chh = ch ;}
        }//for
             System.out.println(chh); 
        }//main
    }
    
    0 讨论(0)
  • 2021-01-18 03:37

    In continuation to the pseudo-code what you've written try the below written code:-

    public static void fetchFrequency(int[] arry) {
            Map<Integer, Integer> newMap = new TreeMap<Integer, Integer>(Collections.reverseOrder());
            int num = 0;
            int count = 0;
            for (int i = 0; i < arry.length; i++) {
                if (newMap.containsKey(arry[i])) {
                    count = newMap.get(arry[i]);
                    newMap.put(arry[i], ++count);
                } else {
                    newMap.put(arry[i], 1);
                }
            }
            Set<Entry<Integer, Integer>> set = newMap.entrySet();
            List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
            Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
    
                @Override
                public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                    return (o2.getValue()).compareTo(o1.getValue());
                }
            });
    
            for (Map.Entry<Integer, Integer> entry : list) {
                System.out.println(entry.getKey() + " ==== " + entry.getValue());
                break;
            }
            //return num;
        }
    
    0 讨论(0)
  • 2021-01-18 03:40
    public static void main(String[] args) {
    
       int n;
    
       int[] arr;
    
        Scanner in = new Scanner(System.in);
        System.out.println("Enter Length of Array");
        n = in.nextInt();
        arr = new int[n];
        System.out.println("Enter Elements in array"); 
    
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
    
        int greatest = arr[0];
    
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > greatest) {
                greatest = arr[i];
            }
    
        } 
    
        System.out.println("Greatest Number " + greatest);
    
        int count = 0;
    
        for (int i = 0; i < arr.length; i++) {
            if (greatest == arr[i]) {
                count++;
            }
        }
    
        System.out.println("Number of Occurance of " + greatest + ":" + count + " times");
    
        in.close();
    }
    
    0 讨论(0)
提交回复
热议问题