FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/src/main/java/com/thealgorithms/maths/Mode.java at master · sohamcodes-ctrl/Java · GitHub
sohamcodes-ctrl
Java
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
thealgorithms
/
maths
/
Mode.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
51 lines (44 loc) · 1.49 KB
Breadcrumbs
Java
/
src
/
main
/
java
/
com
/
thealgorithms
/
maths
/
Mode.java
Copy path
File metadata and controls
51 lines (44 loc) · 1.49 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package
com
.
thealgorithms
.
maths
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
Collections
;
import
java
.
util
.
HashMap
;
import
java
.
util
.
List
;
import
java
.
util
.
Map
;
/**
* Utility class to calculate the mode(s) of an array of integers.
* <p>
* The mode of an array is the integer value(s) that occur most frequently.
* If multiple values have the same highest frequency, all such values are returned.
* </p>
*/
public
final
class
Mode
{
private
Mode
() {
}
/**
* Computes the mode(s) of the specified array of integers.
* <p>
* If the input array is empty, this method returns {@code null}.
* If multiple numbers share the highest frequency, all are returned in the result array.
* </p>
*
* @param numbers an array of integers to analyze
* @return an array containing the mode(s) of the input array, or {@code null} if the input is empty
*/
public
static
int
[]
mode
(
final
int
[]
numbers
) {
if
(
numbers
.
length
==
0
) {
return
null
;
}
Map
<
Integer
,
Integer
>
count
=
new
HashMap
<>();
for
(
int
num
:
numbers
) {
count
.
put
(
num
,
count
.
getOrDefault
(
num
,
0
) +
1
);
}
int
max
=
Collections
.
max
(
count
.
values
());
List
<
Integer
>
modes
=
new
ArrayList
<>();
for
(
final
var
entry
:
count
.
entrySet
()) {
if
(
entry
.
getValue
() ==
max
) {
modes
.
add
(
entry
.
getKey
());
}
}
return
modes
.
stream
().
mapToInt
(
Integer
::
intValue
).
toArray
();
}
}
Back
|
FazBrowse Home
|
New Git URL