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.
之前也有类似得题,找出出现次数大于一般的元素,两道题一个想法。
public class Solution { public List<Integer> majorityElement(int[] nums) { List<Integer> list = new ArrayList(); int[][] num = new int[2][2]; num[0][1] = -1; num[1][1] = -1; for (int i = 0; i < nums.length; i++){ if (num[0][1] != -1 && num[0][0] == nums[i]){ num[0][1]++; } else if (num[1][1] != -1 && num[1][0] == nums[i]){ num[1][1]++; } else if (num[0][1] < 1){ num[0][0] = nums[i]; num[0][1] = 1; } else if (num[1][1] < 1){ num[1][0] = nums[i]; num[1][1] = 1; } else { num[0][1]--; num[1][1]--; } } num[0][1] = 0; num[1][1] = 0; for (int i = 0; i < nums.length; i++){ if (num[0][0] == nums[i]){ num[0][1]++; } else if (num[1][0] == nums[i]){ num[1][1]++; } } if (num[0][1] > nums.length / 3){ list.add(num[0][0]); } if (num[1][1] > nums.length / 3){ list.add(num[1][0]); } return list; } }