题目地址
https://leetcode.com/problems/majority-element/
题目描述
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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
思路
求一个数在数组出现的次数大于数组总长的二分之一, 可以排序, 然后取 length / 2的元素. 也可以hashmap. 也可以用计数法. 计数法代码最简单.
关键点
- hashmap时, 数组length为1要单独判断.
- 计数法, 当key = num时count+1,否则-1.
代码
- 语言支持:Java
// 方法1: 排序.
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
// 方法2: HashMap
class Solution {
public int majorityElement(int[] nums) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap<>();
for (int num: nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
for (int key: map.keySet()) {
if (map.get(key) > n / 2) {
return key;
}
}
return -1;
}
}
// 方法3: 计数法
class Solution {
public int majorityElement(int[] nums) {
int candidate = 0;
int count = 0;
for (int num: nums) {
if (candidate == num) {
count++;
} else {
if (count == 0) {
candidate = num;
count++;
} else {
count--;
}
}
}
return candidate;
}
}
// 如果需要验证
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int candidate = -1;
for (int num: nums) {
if (num == candidate) {
count++;
} else {
if (count == 0) {
candidate = num;
count++;
} else {
count--;
}
}
}
int len = nums.length / 2;
count = 0;
for (int num: nums) {
if (num == candidate) {
count++;
}
}
if (count > len) {
return candidate;
}
return -1;
}
}
网友评论