能否请您帮我解决这段代码,它找到最多的出现值,但我不知道如何找到最少的值。

      int arr[] = new int[] { 2, 3, 5, 4, 5, 4, 4, 2, 4, 3, 5, 4, 2, 4, 2, 4, 2, 2, 18 };
      System.out.println("Most Occurs : " + findElementThatOccursMostly(arr));
      System.out.println("Fewest Occurs : " + findElementThatOccursMin(arr));
     // a shorting array that finds the most occurs value which is 4
     // but can't find the fewest occur number which is 18(only once)
     }

    int findElementThatOccursMostly(int arr[]) {
    int tempOccurrences = 0;
    int tempElement = 0;
    int mostOccurrences = 0;
    int mostElement = 0;
    for (int i = 0; i < arr.length; i++) {
        if (tempElement == arr[i]) {
            tempOccurrences++;
            if (tempOccurrences > mostOccurrences) {
                mostOccurrences = tempOccurrences;
                mostElement = tempElement;
            }
        } else {
            tempOccurrences = 1;
            tempElement = arr[i];
        }
    }
    return mostElement;
}

最佳答案

我还是找不到解决上面代码的问题的方法,这是我的想法,用另一种方法来完成这两个任务:

public static void main(String[] args) {
    List<Integer> list = Arrays.asList(2, 3, 5, 4, 5, 4, 4, 2, 4, 3, 5, 4, 2, 4, 2, 4, 2, 2, 18);
    System.out.println(mostCommon(list));
    System.out.println(lessCommon(list));
}

public static <T> T mostCommon(List<T> list) {
    Map<T, Integer> map = new HashMap<>();

    for (T t : list) {
        Integer val = map.get(t);
        map.put(t, val == null ? 1 : val + 1);
    }

    Map.Entry<T, Integer> max = null;

    for (Map.Entry<T, Integer> e : map.entrySet()) {
        if (max == null || e.getValue() > max.getValue())
            max = e;
    }

    return max.getKey();
}

public static <T> T lessCommon(List<T> list) {
    Map<T, Integer> map = new HashMap<>();

    for (T t : list) {
        Integer val = map.get(t);
        map.put(t, val == null ? 1 : val + 1);
    }

    Map.Entry<T, Integer> max = null;

    for (Map.Entry<T, Integer> e : map.entrySet()) {
        if (max == null || e.getValue() < max.getValue())
            max = e;
    }

    return max.getKey();
}

10-05 21:30