File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
Leetcode/src/com/practise Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ /*
3+
4+ Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
5+
6+ You may assume that the array is non-empty and the majority element always exist in the array.
7+
8+ Example 1:
9+
10+ Input: [3,2,3]
11+ Output: 3
12+ Example 2:
13+
14+ Input: [2,2,1,1,1,2,2]
15+ Output: 2
16+
17+ Solution :
18+ runtime complexity : o(n^2)
19+ space complexity : o(1)
20+ */
21+
22+
23+ package com .practise ;
24+
25+ public class MajorityElement {
26+
27+ public int majorityElement (int [] nums ) {
28+
29+ if (nums .length < 2 ){
30+ return nums [0 ];
31+ }
32+
33+ int largestNum = 0 ;
34+ int maxCount = 0 ;
35+
36+ for (int i =0 ; i < nums .length ;i ++){
37+ int count =0 ;
38+ for (int j =i ;j < nums .length ;j ++){
39+ if (nums [i ]==nums [j ]){
40+ count ++;
41+ }
42+
43+ if (count >=maxCount ){
44+ maxCount = count ;
45+ largestNum = nums [i ];
46+ }
47+ }
48+ }
49+ return largestNum ;
50+ }
51+ }
You can’t perform that action at this time.
0 commit comments