[抄题]:
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.
[暴力解法]:
时间分析:
空间分析:
[奇葩输出条件]:
[奇葩corner case]:
[思维问题]:
以为n个元素的出现次数一定也要用n个变量来存。
[一句话思路]:
用一个count来存最多次数,节约空间
[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):
[画图]:
[一刷]:
- 看清要求,最后返回的是major元素,而不是次数
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分钟肉眼debug的结果]:
[总结]:
用一个count的++--来节约存储空间
[复杂度]:Time complexity: O(n) Space complexity: O(1)
[英文数据结构或算法,为什么不用别的数据结构或算法]:
[关键模板化代码]:
[其他解法]:
[Follow Up]:
[LC给出的题目变变变]:
229. Majority Element II 数学题,也是醉了
[代码风格] :
class Solution { public int majorityElement(int[] nums) { //ini int major = nums[0]; int count = 1; //1 - n for (int i = 1; i < nums.length; i++) { //nums[i] != major, count--,if count == 0 if (nums[i] != major) { if (count == 0) { major = nums[i]; count++; } count--; }else { //nums[i] == major, count++ count++; } } return major; }}