这段代码应该返回最常见元素的频率。

huangapple go评论77阅读模式
英文:

This Code of mine should return the frequency of the most common element

问题

Arrays.sort(arr);
int max = 1, m = 1;
for (int i = 1; i < arr.length; i++) {
    if (arr[i] == arr[i - 1]) {
        max++;
    } else {
        if (max > m) {
            m = max;
            max = 1;
        }
    }
}
if (max > m) {
    m = max;
}

return m;

这是我制作的一个函数。它应该返回最常见的元素出现的次数。例如,如果数组是 1,2,2,3,3,3,则应该返回 3。但是它在许多情况下都失败,例如对于输入 1 2 3 1 2 3 3 3,这段代码失败并返回 5,这是错误的输出。

英文:
Arrays.sort(arr);
int max=1,m=1;
for(int i=1;i&lt;arr.length;i++){
    if(arr[i]==arr[i-1]){
        max++;
    }
    else{
        if(max&gt;m){
            m=max;
            max=1;
        }
       
    }
}
if(max&gt;m){
    m=max;
   
}

return m;

This is a function that I have made. This should return the number of times the most frequent element occurs. E.g if the array is 1,2,2,3,3,3 , then it should return 3. But it fails in many cases, e.g for the input 1 2 3 1 2 3 3 3, this code fails and returns 5, which is the wrong output.

答案1

得分: 3

以下是翻译好的内容:

我可以为您编写代码,使用映射接口来回答您的问题。我将检查每个值,如果已经存在该值的键,它将将该值增加1。如果没有,则会创建该键并为其分配值1。

完成后,我只需要询问映射最大的值是多少,这是我认为您想要的。如果您想要的话,我还可以返回出现最频繁的值。

以下是经过测试的代码。一个用于工作方法的类,然后是带有main方法的驱动程序类。

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;

public class FindMostFrequent {

	public static Integer returnFromArrayHighestFrequency(int[] inArray) {
		HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();

		for (int i = 0; i < inArray.length; i++) {
			if (hashMap.containsKey(inArray[i])) {
				hashMap.put(inArray[i], hashMap.get(inArray[i]) + 1);
			} else {
				hashMap.put(inArray[i], 1);
			}
		}
		Integer maxValue = Collections.max(hashMap.values());

		return maxValue;
	}

}

以下是驱动程序类:

public class Main {

	public static void main(String[] args) {
		int[] testArray = { 1, 2, 2, 3, 3, 3 };

		Integer max = FindMostFrequent.returnFromArrayHighestFrequency(testArray);
		System.out.println("最高频率为:" + max);

	}
}

我喜欢这种技术,因为它使您可以轻松地获取最小值或其他任何您想要的值及其键。

英文:

I can code it up for you to answer your question using the map interface. I will check each value and if there is already a key for that value, it will increment the value by 1. If not, then it will create the key and assign it a value of 1.

When finished, I only need to ask the map what the largest value was which is what I think you are after. And I can also return the value that was the most frequent, if you want.

Here is the tested code. One class for the working method and then the driver class with main method

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;

public class FindMostFrequent {

	public static Integer returnFromArrayHighestFrequency(int[] inArray) {
		HashMap&lt;Integer, Integer&gt; hashMap = new HashMap&lt;Integer, Integer&gt;();

		for (int i = 0; i &lt; inArray.length; i++) {
			if (hashMap.containsKey(inArray[i])) {
				hashMap.put(inArray[i], hashMap.get(inArray[i]) + 1);
			} else {
				hashMap.put(inArray[i], 1);
			}
		}
		Integer maxValue = Collections.max(hashMap.values());

		return maxValue;
	}

}

And here is the driver class:

	public static void main(String[] args) {
		int[] testArray = { 1, 2, 2, 3, 3, 3 };

		Integer max = FindMostFrequent.returnFromArrayHighestFrequency(testArray);
		System.out.println(&quot;highest frequency is:  &quot; + max);

	}

I like this technique because it allows you to easily get the minimum or another other value and its key that you want.

答案2

得分: 1

另一种使用流的方法,基本上使用映射来跟踪出现频率,并在对该映射排序后获取最高值。

public static Long getMostFrequentCount(int... values) {
    return Arrays.stream(values).boxed().collect(Collectors.groupingBy(Function.identity(),
            Collectors.counting())).values().stream().max(Long::compareTo).orElse(null);
}

编辑:感谢 @saka1029 的出色建议,变得更好了。

英文:

Another way using streams, which basically uses a map to track the frequency of occurrences and grabs the highest value after sorting that map.

public static Long getMostFrequentCount( int ... values ) {
    return Arrays.stream(values).boxed().collect(Collectors.groupingBy(Function.identity(),
            Collectors.counting())).values().stream().max(Long::compareTo).orElse( null );
}

EDIT: Made better thanks to @saka1029 's excellent suggestion

答案3

得分: 1

对数组进行排序,然后计算相同数字的连续出现次数是一个不错的想法。您的逻辑并不太合理。

您需要跟踪当前连续出现的长度以及最长连续出现的长度。当数组中的值与前一个值不同时,您的当前连续出现应该被重置;而当当前连续出现的长度超过最长连续出现时,您的最长连续出现应该被更新。

可以像这样实现:

if (arr.length==0) {
    return 0;
}
Arrays.sort(arr);
int currentRun = 1;
int longestRun = 1;
for (int i = 1; i < arr.length; i++){
    if (arr[i]==arr[i-1]){
        ++currentRun;
        if (currentRun > longestRun) {
            longestRun = currentRun;
        }
    } else {
        currentRun = 1;
    }
}

return longestRun;
英文:

Sorting the array first and counting runs of the same number is a good idea. Your logic doesn't quite make sense through.

You need to keep track of the length of the current run, and the length of the longest run. Your current run should get reset when the value in the array is different to the previous value; and your longest run should be updated when the current run is longer than it.

Something like this:

if (arr.length==0) {
    return 0;
}
Arrays.sort(arr);
int currentRun = 1;
int longestRun = 1;
for (int i = 1; i &lt; arr.length; i++){
    if (arr[i]==arr[i-1]){
        ++currentRun;
        if (currentRun &gt; longestRun) {
            longestRun = currentRun;
        }
    } else {
        currentRun = 1;
    }
}

return longestRun;

答案4

得分: 0

这可能是你想要的...
你想要使用的所有数字都包含在数组a中。

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6, 7, 7, 7, 7};
        int count = 1, tempCount;
        int popular = a[0];
        int temp = 0;
        for (int i = 0; i < (a.length - 1); i++) {
            temp = a[i];
            tempCount = 0;
            for (int j = 1; j < a.length; j++) {
                if (temp == a[j])
                    tempCount++;
            }
            if (tempCount > count) {
                popular = temp;
                count = tempCount;
            }
        }
        System.out.println(popular);
    }
}
英文:

This might be what you want...
All of the numbers you want to use is contained inside of the array a.

public class Main {
public static void main(String[] args) {
    int[] a = {1,2,3,4,5,6,7,7,7,7};
    int count = 1, tempCount;
    int popular = a[0];
    int temp = 0;
    for (int i = 0; i &lt; (a.length - 1); i++) {
        temp = a[i];
        tempCount = 0;
        for (int j = 1; j &lt; a.length; j++) {
            if (temp == a[j])
                tempCount++;
        }
        if (tempCount &gt; count) {
            popular = temp;
            count = tempCount;
        }
    }
    System.out.println(popular);
}
}

答案5

得分: 0

你的逻辑完全正确,除了一行代码。 ==> 如果(max>m)。
在这种情况下,如果max == m,你没有重置max的值。

if(max&gt;=m){ 替换 if(max&gt;m){

英文:

your logic is totally correct except one line. ==> if(max>m).
In this case you are not resetting the value of max if max == m.

replace if(max&gt;m){ with if(max&gt;=m){

答案6

得分: 0

你需要在每次迭代中将 maxm 进行比较。在这里使用 continue 简化了逻辑。在空数组上打印 -1。

int[] arr = {1, 2, 3, 1, 2, 3, 3, 3};
Arrays.sort(arr);
int max = 1;
int m = arr.length == 0 ? -1 : 1;
for (int i = 1; i < arr.length; i++) {
    if (arr[i] == arr[i - 1]) {
        max++;
        if (max > m) {
            m = max;
        }
        continue;
    }
    max = 1;
}
System.out.println(m);

打印结果为

4
英文:

You need to check max against m for each iteration. And the use of continue here simplifies the logic. Prints -1 on an empty array.

int[] arr = {1, 2, 3, 1, 2, 3, 3, 3}; 
Arrays.sort(arr);                       
int max = 1;                            
int m = arr.length == 0 ? -1 : 1;                             
for (int i = 1; i &lt; arr.length; i++) {  
	if (arr[i] == arr[i - 1]) {         
		max++;                          
		if (max &gt; m) {                  
			m = max;                    
		}                               
		continue;                       
	}                                   
	max = 1;                            
}                                       
                                                                         
System.out.println(m);

Prints

4

</details>



huangapple
  • 本文由 发表于 2020年8月30日 05:32:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63651973.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定