算法准备-4.15
1. 数组中超过一半的数字(摩尔投票法)
-
描述:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字
-
未解思路:此题采用分治算法,在原数组中超过一半的数字,在等分的左右两数组中至少有一个中也超过了一半,而且因为是超过一半,所以两个等分数组中都存在此元素
-
新学思路:摩尔投票法:摩尔投票法基于当一个数的重复次数超过数组长度的一半,每次将两个不相同的元素删除,最终剩下的就是要找的数。用votes表示票数,初始化为0,当votes为0时,将当前元素设为众数,遍历数组,与其相等的,votes加一,否则减一。
-
题解:
class Solution { public int majorityElement(int[] nums) { int x=0; int votes=0; for(int i=0;i<nums.length;i++) { if(votes==0) { x=nums[i]; } votes+=x==nums[i]?1:-1; } return x; } }
-
扩展:此题还有一种比较常见的解法就是先对数组进行排序,得到新数组的中位数即为众数
class Solution { public int majorityElement(int[] nums) { sort(nums); int mid=(nums.length-1)/2; return nums[mid]; } public void sort(int[] nums){ for(int i=0;i<nums.length;i