示例:
输入:nums = [3,2,3]
输出:3
public static void main(String[] args) {
int[] nums = {2,2,1,1,1,2,2};
//方式一:
method1(nums);
//方式二:
method2(nums);
//方式三:摩尔投票法
method3(nums);
}
/**
* 方式一:排序取中间值即可
*/
private static int method1(int[] nums) {
// 方式一:排序取中间值即可
Arrays.sort(nums);
System.out.println("way1: " + nums[nums.length / 2]);
return nums[nums.length / 2];
}
原理:
/**
* 方式二:使用HashMap实现
*/
private static int method2(int[] nums) {
// 使用HashMap实现
Map<Integer, Integer> map = new HashMap<>();
// 遍历数组,将数组中的元素作为key,出现的次数作为value
for (int num : nums) {
Integer count = map.get(num);
if (count == null) {
count = 0;
}
map.put(num, ++count);
if (count > nums.length / 2) {
System.out.println("way2: " + num);
return num;
}
}
// 如果没有找到,返回-1
return -1;
}
原理:
/**
* 摩尔投票法-核心就是对拼消耗
* 这想法真的是太妙了,而且还是一次遍历就解决了,而且空间复杂度还是O(1)。
* @param nums
* @return
*/
private static int method3(int[] nums) {
// 摩尔投票法-核心就是对拼消耗
int count = 0;
int candidate = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
System.out.println("way3: " + candidate);
return candidate;
}
原理: