如何在Java中找到短路数组中最少和最多的数字

时间:2017-11-02 19:41:00

标签: java arrays sorting

你可以帮我解决一下这个代码吗,它找到了最有价值但是我无法弄清楚我怎么能找到最少的代码。

      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;
}

5 个答案:

答案 0 :(得分:1)

我无论如何都无法用上面的代码来解决你的问题所以,这是我的想法用另一种方式来做到这两点:

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();
}

答案 1 :(得分:1)

您可以对元素进行排序,然后对其进行排序。所以[1,4,2,6,4] - &gt; [1,2,4,4,6]。如果你看到1然后你看到2,你将minCounter设置为1,然后从2你看到4,minCounter仍然是1. 4到4,这是2次出现所以你不更新。最后你返回位置。显然你可以操纵它来查找最大值。

答案 2 :(得分:1)

您的实际方法无法实现。

您希望找到最多/较不频繁的号码,而您会找到长度最多/较少的号码。

实际上,将4作为最常见的数字返回是巧合 4出现了7次,但较长的序列为4

通过在单个系列中添加任意数字5次来更改输入数组,您会看到它现在将被您的方法返回为最常用的值,即使全局此数字显示为少于4。< / p>

例如:

int arr[] = new int[] { 2, 3, 5, 4, 5, 4, 4, 2, 4, 3, 5, 4, 2, 4, 2, 4, 2, 2, 18, 18, 18, 18, 18 };

应该显示问题。

要解决您的要求,请引入地图以存储每个数字的频率,然后使用此地图检索最多且频率较低的数字。
请注意,要查找与max和min键值关联的值,您可以利用提供Stream.min() / Stream.max()函数的Java 8,您可以将其作为{Entry.comparingByValue()传递给Comparator {1}}论证。

这是完整的代码:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;

public class FindMinAndMaxFrequency {

    public static void main(String[] args) {
      int arr[] = new int[] { 2, 3, 5, 4, 5, 4, 4, 2, 4, 3, 5, 4, 2, 4, 2, 4, 2, 2, 18, 18, 18, 18, 18 };

      Map<Integer, Integer> frequenciesByNumber = computeFrequency(arr);
      System.out.println("Most Occurs : " + findElementThatOccursMostly(frequenciesByNumber));
      System.out.println("Fewest Occurs : " + findElementThatOccursMin(frequenciesByNumber));
    }

    private static Map<Integer, Integer> computeFrequency(int[] array) {
      Map<Integer, Integer> frequencesByValue = new HashMap<>();
      for (int i : array) {
        int actualFrequency = frequencesByValue.computeIfAbsent(i, key -> 0);
        frequencesByValue.put(i, ++actualFrequency);
      }
      return frequencesByValue;
    }

    static int findElementThatOccursMostly(Map<Integer, Integer> frequenciesByNumber) {    
      Optional<Entry<Integer, Integer>> max = frequenciesByNumber.entrySet()
        .stream()
        .max(Entry.comparingByValue());
      return max.get().getKey();
    }

    static int findElementThatOccursMin(Map<Integer, Integer> frequenciesByNumber) {    
      Optional<Entry<Integer, Integer>> max = frequenciesByNumber.entrySet()
        .stream()
        .min(Entry.comparingByValue());
      return max.get().getKey();
    }    
}

<强>输出

  

最常发生:4

     

最少发生:3

答案 3 :(得分:1)

这是我能找到的最荒谬的基于流的方式,不包括自定义缩减器或收集器;)

    Map<Integer, Integer> counts = Arrays.stream(arr).sorted().boxed()
            .collect(Collectors.groupingBy(Function.identity()))
            .entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue().size()));
    System.out.println(counts.entrySet().stream().min(Comparator.comparing(java.util.Map.Entry::getValue)));
    System.out.println(counts.entrySet().stream().max(Comparator.comparing(java.util.Map.Entry::getValue)));

不确定我是否会在生产中使用它;)

答案 4 :(得分:0)

所以我在你的问题上工作了几个小时,最后从头开始制作了以下代码:

int findElementThatOccursMin(int[] array) {
    bubbleSort(array);
    int counter = 1; //counts the occurences

    int min_occ=100; //minimum occurences
    /*here put a starting value that is high relatively to the times a 
    number is in the matrix*/

    int num=array[0]; //the number that we want
    //start with 0 index in case the array has 1 element
    for (int i = 0; i <= array.length - 1; i++) {
        if (i == array.length - 1) { //avoid out of bounds exc
            if (array[i]!=array[i-1]) {
                num=array[i]; //in case it is one in last position
                min_occ=1;
            }
            else { //in case it is multiple times in last positions of array
                if (counter < min_occ) {
                min_occ=counter;
                num = array[i];
                }
            }
            break;
        }
        if (array[i] == array[i + 1]) {
            counter++;
        }
        else {
            if (counter < min_occ) {
                min_occ=counter;
                num = array[i];
            }
            counter=1;
        }
    }
    System.out.println("Amount of min : "+min_occ+" times");
    //helped me see how many times the element was in the array
    return num;
}

我根据逻辑编写了这段代码,显然你可以看到我使用冒泡排序对元素进行排序,并且&#34;坚持&#34;他们在邻近的牢房里。这不是编写代码的正确方法,但我这样做是为了用一个有效的代码来回答你的问题。

如果你需要,请点击泡泡排:

static void bubbleSort(int[] arr) {
    int n = arr.length;
    int temp = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 1; j < (n - i); j++) {
            if (arr[j - 1] > arr[j]) {
                //swap elements  
                temp = arr[j - 1];
                arr[j - 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

PS。我不确定代码是否100%正常工作。我用很多组合测试了很多次,效果很好。如果发现错误,我很乐意听到!