# LeetCode—求众数

## 求众数

输入: [3,2,3]

输入: [2,2,1,1,1,2,2]

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

class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> map = countNums(nums);
Map.Entry<Integer,Integer> majorityEntry = null;
for(Map.Entry<Integer,Integer> entry:map.entrySet()){
if(majorityEntry==null||entry.getValue()>majorityEntry.getValue()){
majorityEntry = entry;
}
}
return majorityEntry.getKey();

}
private Map<Integer,Integer> countNums(int[] nums){
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int num:nums){
if(!map.containsKey(num))
map.put(num,1);
else{
map.put(num,map.get(num)+1);
}
}
return map;
}
}

class Solution {
private int countInRange(int[] nums, int num, int lo, int hi) {
int count = 0;
for (int i = lo; i <= hi; i++) {
if (nums[i] == num) {
count++;
}
}
return count;
}

private int majorityEleme***ec(int[] nums, int lo, int hi) {
// base case; the only element in an array of size 1 is the majority
// element.
if (lo == hi) {
return nums[lo];
}

// recurse on left and right halves of this slice.
int mid = (hi-lo)/2 + lo;
int left = majorityEleme***ec(nums, lo, mid);
int right = majorityEleme***ec(nums, mid+1, hi);

// if the two halves agree on the majority element, return it.
if (left == right) {
return left;
}

// otherwise, count each element and return the "winner".
int leftCount = countInRange(nums, left, lo, hi);
int rightCount = countInRange(nums, right, lo, hi);

return leftCount > rightCount ? left : right;
}

public int majorityElement(int[] nums) {
return majorityEleme***ec(nums, 0, nums.length-1);
}
}



• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

to_be_better_one

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
01-21 2325

01-10 401
11-05 6500
07-01 863
10-27 7322
01-14 599
11-06 4043
03-30 4975