# LeetCode 169. Majority Element题目分析代码

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Credits:Special thanks to @ts for adding this problem and creating all test cases. Subscribe to see which companies asked this question.

# 代码

```public class Solution {
public int majorityElement(int[] nums) {
int count = 0, candidate = -1;
for (int i = 0; i < nums.length; i++) {
if (count == 0) {
candidate = nums[i];
count = 1;
} else if (candidate == nums[i]) {
count++;
} else {
count--;
}
}
return candidate;
}
}```

Paste_Image.png

## 方法二 排序法

```// Sorting
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length/2];
}```

## 方法三

```public int majorityElement2(int[] nums) {
Map<Integer, Integer> myMap = new HashMap<Integer, Integer>();
//Hashtable<Integer, Integer> myMap = new Hashtable<Integer, Integer>();
int ret=0;
for (int num: nums) {
if (!myMap.containsKey(num))
myMap.put(num, 1);
else
myMap.put(num, myMap.get(num)+1);
if (myMap.get(num)>nums.length/2) {
ret = num;
break;
}
}
return ret;
}```

381 篇文章35 人订阅

0 条评论

## 相关文章

18430

### Java基础——Map接口

通常来说，Map是一个由键值对组成的数据结构，且在集合中每个键是唯一的。下面就以K和V来代表键和值，来说明一下java中关于Map的几个问题。

12220

26190

42250

12730

440120

11920

45280

16610

28390