8

我必须在双数组中找到出现次数最多的元素。我是这样做的:

int max = 0;
for (int i = 0; i < array.length; i++) {
       int count = 0;
       for (int j = 0; j < array.length; j++) {
         if (array[i]==array[j])
             count++;
   }
  if (count >= max)
      max = count;
 }

程序可以运行,但是太慢了!我必须找到更好的解决方案,有人可以帮助我吗?

4

12 回答 12

13

更新:

  • 正如 Maxim 所指出的,在这里使用HashMap将是比Hashtable更合适的选择。
  • 这里的假设是您不关心并发性。如果需要同步访问,请改用ConcurrentHashMap

您可以使用HashMap来计算双精度数组中每个唯一元素的出现次数,这将:

  • 以线性O(n)时间运行,并且
  • 需要O(n)空间

伪代码将是这样的:

  • 遍历数组的所有元素一次:O(n)
    • 对于访问的每个元素,检查其键是否已存在于 HashMap 中:O(1),已摊销
    • 如果没有(第一次看到这个元素),那么将它作为 [key: this element, value: 1] 添加到你的 HashMap 中。O(1)
    • 如果确实存在,则将键对应的值加 1。O(1),摊销
  • 完成构建 HashMap 后,遍历映射并找到具有最高关联值的键 - 这就是出现次数最多的元素。在)

部分代码解决方案,让您了解如何使用 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);
        }
    }

我将作为练习离开,以了解如何在之后遍历 HashMap 以找到具有最高值的键;但如果你遇到困难,只需添加另一条评论,我会给你更多提示 =)

于 2012-11-25T16:34:45.717 回答
7

使用Collections.frequency选项:

 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");

输出:

The number 12 happens 10 times

于 2012-11-25T16:42:17.157 回答
6

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));
于 2020-05-07T12:29:36.763 回答
5

我会建议另一种方法。我不知道这是否会更快。

快速排序数组。使用内置的 Arrays.sort() 方法。

现在比较相邻的元素。考虑这个例子:

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

当相邻元素不相等时,您可以停止计算该元素。

于 2012-11-25T16:43:49.457 回答
1

解决方案 1:使用 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

*/

解决方案 2:使用计数数组

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
}
于 2018-05-31T14:40:50.880 回答
1

这是一个Java解决方案-

        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");
于 2020-08-13T10:49:34.757 回答
1
int[] array = new int[] { 1, 2, 4, 1, 3, 4, 2, 2, 1, 5, 2, 3, 5 };

Long max = Arrays.stream(array).boxed().collect(Collectors.groupingBy(i -> i, Collectors.counting())).values()
                .stream().max(Comparator.comparing(Function.identity())).orElse(0L);
    
于 2021-08-09T18:00:33.447 回答
0
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();
}
于 2017-07-11T15:06:00.520 回答
0

继续您编写的伪代码,请尝试以下编写的代码:-

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;
    }
于 2017-10-26T17:23:57.333 回答
0

这就是我在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);
    }
}
于 2019-02-25T05:45:54.283 回答
-1

您可以在一个循环中解决此问题,而无需使用 HashMap 或 O(1) 空间复杂度的任何其他数据结构。

初始化两个变量 count = 0 和 max = 0(如果数组中有负数,则初始化 Integer.MIN_VALUE)

这个想法是您将扫描数组并检查当前数字,

  • 如果它小于你当前的最大值......那么什么都不做
  • 如果它等于您的最大值 ...然后增加计数变量
  • 如果它大于您的最大值..然后将最大值更新为当前数字并将计数设置为 1

代码:

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;
    }
}
于 2017-10-06T04:39:11.973 回答
-1

这是 Ruby 解决方案:

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"])

输出:

"12 occured 10 times"
于 2020-08-12T16:19:28.740 回答