Java - 打印出数组中发生最少的元素

时间:2014-01-26 00:13:57

标签: java arrays

我得到一个大小为10的数组,我想编写一个程序,打印出发生次数最少的元素和它们出现的次数。

例如阵列:1 2 3 3 2 2 4 4 5 4 程序应打印..元素:1 5,出现次数应为1

我到目前为止打印出的次数最多,只打印出一个元素。

public class Question3 {

  public static void main (String[] args) { 

     int[] testarray = {1,2,3,3,2,2,4,4,5,4};
     int count = 0;
     int bigCount = 10;

      for (int i=0; i < array.length; i++) {
        for (int j=0; j < array.length; j++) {
          if(array[j] == array[i]) {
             count++;
        }
    }
        if(count > bigCount) {
          bigCount = count;
          array[i] = random;
      }
    }
 System.out.println("num of elements and occurences: " + maxCount);
  }
}

3 个答案:

答案 0 :(得分:3)

您可以尝试使用其他数组来存储最少的ocurring元素。这个数组的长度等于到“原始”数组的长度(如果所有元素只出现一次,所有元素都是最少的数据):

public static void main(String[] args)
{
    int[] array = { 1, 2, 3, 3, 2, 2, 4, 4, 5, 4 };
    int count = 0;
    int maxCount = 10;
    int[] results = new int[array.length];
    int k = 0; // To keep index in 'results'

    // Initializing 'results', so when printing, elements that -1 are not part of the result
    // If your array also contains negative numbers, change '-1' to another more appropriate
    for (int i = 0; i < results.length; i++) {
        results[i] = -1;
    }

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

        if (count <= maxCount) { // <= so it admits number with the SAME number of occurrences
            maxCount = count;
            results[k++] = array[i]; // Add to 'results' and increase counter 'k'
        }
        count = 0; // Reset 'count'
    }

    // Printing result
    for (int i : results) {
        if (i != -1) {
            System.out.println("Element: " + i + ", Number of occurences: " + maxCount);
        }
    }
}

<强>输出:

Element: 1, Number of occurences: 1
Element: 5, Number of occurences: 1

编辑/注意:

正如@Happy评论的那样,由于嵌套的for循环,你的程序复杂性很差 O(n 2 。你可以用另一种方式思考这一点。

答案 1 :(得分:3)

你需要一个数据结构来保存每个独特的元素并计算它,Map<Integer,Integer>可能是你最好的选择。像你现在一样迭代你的数组,并保持计数。像这样:

public static void main(String[] args) {

    int[] array = {1,2,3,3,2,2,4,4,5,4};
    //create the map like this: <Element,Count>
    Map<Integer, Integer> counts = new HashMap<>();

    for (Integer i : array) {
        if (counts.get(i) == null) {
            counts.put(i, 1);
        } else {
            counts.put(i, counts.get(i) + 1);
        }
    }

    //find min value by sorting values and taking top element
    List<Integer> cs = new ArrayList<Integer>(counts.values());
    Collections.sort(cs);
    int minVal = cs.get(0);

    //find elements with minVal as their count
    List<Integer> minElements = new ArrayList<>();
    for (Entry<Integer, Integer> entry : counts.entrySet()) {
        if (entry.getValue() == minVal) {
            minElements.add(entry.getKey());
        }
    }
    //spit out each element and the count
    for (Integer i : minElements) {
        System.out.println("Element: " + i + " Number of occurences: "
                + minVal);
    }

}

效率不是很高,但它完成了。

答案 2 :(得分:1)

你必须存储你在if语句中找到的所有元素(通过一些调整),而不是像你现在那样只存储一个元素。

修改

有三个步骤:

  • 查找数组中每个元素的数量。您可以使用Map<Integer, Integer>,将元素作为键和元素的数字存储为数组。 您可以使用以下代码:
Map<Integer, Integer> v = new HashMap<>();
v.put(theElementOfTheArray, theNumberItAppears);
  • 使用Map

  • Map.EntrySet()中找到较小的值
  • 保留值等于第2步结果的元素。

我写了算法,但我更喜欢让你试试。如果您有其他问题,请不要犹豫。