leetcode 面试题 17.10. 主要元素
数组中占比超过一半的元素称之为主要元素。给你一个 整数 数组,找出其中的主要元素。若没有,返回 -1
。请设计时间复杂度为 O(N)
、空间复杂度为 O(1)
的解决方案。
示例 1:
输入:[1,2,5,9,5,9,5,5,5] 输出:5
示例 2:
输入:[3,2] 输出:-1
示例 3:
输入:[2,2,1,1,1,2,2] 输出:2
方法一:利用哈希统计每个元素出现的次数
/**
* 方法一:哈希
*
* @param nums
* @return
*/
public static int majorityElement01(int[] nums) {
if (nums == null || nums.length == 0) return 0;
Map<Integer, Integer> integerMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
integerMap.put(nums[i], integerMap.getOrDefault(nums[i], 0) + 1);
if (integerMap.get(nums[i]) > nums.length / 2) return nums[i];
}
return -1;
}
方法二:利用摩尔投票
当一个数的重复次数超过数组长度的一半,每次将两个不相同的数删除,最终剩下的就是要找的数
/**
* 摩尔投票法
*
* @param nums
* @return
*/
public static int majorityElement(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int target = nums[0];
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == target) count++;
else {
count--;
if (count <= 0) {
target = nums[i];
count = 1;
}
}
}
count = 0;
for (int num : nums) {
if (num == target) count++;
}
return count > nums.length / 2 ? target : -1;
}
测试用例
public static void main(String[] args) {
int[] nums = new int[]{1, 2, 5, 9, 5, 9, 5, 5, 5};
int majorityElement = MajorityElement.majorityElement(nums);
System.out.println("MajorityElement demo01 result : " + majorityElement);
nums = new int[]{3, 2};
majorityElement = MajorityElement.majorityElement(nums);
System.out.println("MajorityElement demo02 result : " + majorityElement);
nums = new int[]{3, 3, 2};
majorityElement = MajorityElement.majorityElement(nums);
System.out.println("MajorityElement demo03 result : " + majorityElement);
nums = new int[]{3, 2, 2};
majorityElement = MajorityElement.majorityElement(nums);
System.out.println("MajorityElement demo04 result : " + majorityElement);
nums = new int[]{3, 2, 3};
majorityElement = MajorityElement.majorityElement(nums);
System.out.println("MajorityElement demo05 result : " + majorityElement);
nums = new int[]{2, 2, 1, 1, 1, 2, 2};
majorityElement = MajorityElement.majorityElement(nums);
System.out.println("MajorityElement demo06 result : " + majorityElement);
}