章丘做网站的公司,网站建设的基本,有了域名空间怎么做网站,义乌廿三里本题来自#xff1a;力扣-面试经典 150 题
面试经典 150 题 - 学习计划 - 力扣#xff08;LeetCode#xff09;全球极客挚爱的技术成长平台https://leetcode.cn/studyplan/top-interview-150/
题解#xff1a;
class Solution {public int majorityElement(int[] nums) …本题来自力扣-面试经典 150 题
面试经典 150 题 - 学习计划 - 力扣LeetCode全球极客挚爱的技术成长平台https://leetcode.cn/studyplan/top-interview-150/
题解
class Solution {public int majorityElement(int[] nums) {Arrays.sort(nums);return nums[nums.length / 2];
}
思路如下
排序后由于多数多数元素占整个数组的1/2以上。所以数组中间一定是多数元素
题解
class Solution {public int majorityElement(int[] nums) {int key 0;int value 0;for(int x : nums){if(value 0)key x;if(key x)value;elsevalue--;}return key;}
}
思路如下
Boyer-Moore 投票算法,如果我们把众数记为 1把其他数记为 −1将它们全部加起来显然和大于 0从结果本身我们可以看出众数比其他数多。