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.
数组和字符串的分治法: 对返回值的操作(叶结点的+ 非叶结点的), 出口, 分治起始位置, 题目要求--返回值
难点在于从哪分(题目要求的理解? 中间?符号?)和叶结点情况的处理->返回值
见Different Ways to Add Parentheses
public class Solution {
public int majorityElement(int[] nums) {
return helper(nums, 0, nums.length-1);
}
//确定返回值类型(根据在下一次递归中的作用, 或者题目的返回值类型)
private int helper(int[] nums, int lo, int hi) {
//递归出口
if (lo == hi) return nums[lo];
int mid = lo + (hi - lo) / 2;
//分治
int left = helper(nums, lo, mid);
int right = helper(nums, mid+1, hi);
//开始对分治后的小分支进行操作: 根据题目要求用TC写一下, 准备进行返回了
// 优化的好啊, 如果相等不用判断了
if (left == right) return left;
else {
int l = 0, r = 0;
for (int i = lo; i <= hi; i++) {
if (nums[i] == left) l++;
if (nums[i] == right) r++;
}
return l > r ? left : right;
}
}
}
投票法: 根据majority 的特性---考点—提取成算法
public int majorityElement(int[] nums) {
int majority = nums[0], count = 1;
for (int i = 1; i < nums.length; i++) {
if (count == 0) {
majority = nums[i];
count++;
} else if (nums[i] == majority) {
count++;
} else {
count--;
}
}
return majority;
}
hashMap 法键值对
public class Solution {
public int majorityElement(int[] num) {
int n = num.length;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int elem : num) {
if (map.containsKey(elem)) {
map.put(elem, map.get(elem)+1);
}
else {
map.put(elem, 1);
}
}
for (int item : map.keySet()) {
if (map.get(item) > n/2) {
return item;
}
}
return -1;
}
}