Description
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
Solution
|
|
Result
AC
Optimization
|
|
Analyse
这个方法就是MajorityElement的方案的变形,但是要注意,一定开始是把count1和count2从0开始计算,若是都是开始从1开始计算,那么后面要计算count1和count2等于0的时候就会出问题。所以为了统一写法,就在majorityElement里直接改写法。12345678910111213141516public int majorityElement(int[] nums) { int count = 0; int len = nums.length; int n = nums[0]; for (int i = 0; i < len; i++) { if (nums[i] == n) { count++; } else if (count == 0) { n = nums[i]; count = 1; } else { count--; } } return n; }