File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
1
+ //Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
2
+ //You may assume that the array is non-empty and the majority element always exist in the array.
3
+
4
+ class MajorityElement {
5
+ public int majorityElement (int [] nums ) {
6
+ if (nums .length == 1 ) {
7
+ return nums [0 ];
8
+ }
9
+
10
+ HashMap <Integer , Integer > map = new HashMap <Integer , Integer >();
11
+ for (int current : nums ) {
12
+ if (map .containsKey (current ) && map .get (current ) + 1 > nums .length / 2 ) {
13
+ return current ;
14
+ } else if (map .containsKey (current )) {
15
+ map .put (current , map .get (current ) + 1 );
16
+ } else {
17
+ map .put (current , 1 );
18
+ }
19
+ }
20
+
21
+ //no majority element exists
22
+ return -1 ;
23
+ }
24
+ }
Original file line number Diff line number Diff line change
1
+ //Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
2
+ //You may assume that the array is non-empty and the majority element always exist in the array.
3
+
4
+ class MajorityElement {
5
+ public int majorityElement (int [] nums ) {
6
+ if (nums .length == 1 ) {
7
+ return nums [0 ];
8
+ }
9
+
10
+ HashMap <Integer , Integer > map = new HashMap <Integer , Integer >();
11
+ for (int current : nums ) {
12
+ if (map .containsKey (current ) && map .get (current ) + 1 > nums .length / 2 ) {
13
+ return current ;
14
+ } else if (map .containsKey (current )) {
15
+ map .put (current , map .get (current ) + 1 );
16
+ } else {
17
+ map .put (current , 1 );
18
+ }
19
+ }
20
+
21
+ //no majority element exists
22
+ return -1 ;
23
+ }
24
+ }
You can’t perform that action at this time.
0 commit comments