1 parent 8e34f23 commit e2dd8c6Copy full SHA for e2dd8c6
1 file changed
solutions/169. Majority Element/AC_HashMap.java
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 使用HashMap,时间复杂度也是O(n)
3
+ *
4
5
+ */
6
+ public static int majorityElement2(int[] nums){
7
+ Map<Integer, Integer> map = new HashMap<Integer,Integer>();
8
+ int res = 0;
9
+ for(int i = 0; i< nums.length; i++){
10
+ if(!map.containsKey(nums[i])){
11
+ map.put(nums[i], 1);
12
+ }else{
13
+ map.put(nums[i], map.get(nums[i]) + 1);
14
+ }
15
16
+
17
18
+ if(map.get(nums[i]) > nums.length/2){
19
+ res = nums[i];
20
+ break;
21
22
23
+ return res;
24
0 commit comments