题目描述
// 39. 数组中出现次数超过一半的数字
// 力扣
// 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
// 你可以假设数组是非空的,并且给定的数组总是存在多数元素。
// 牛客
// 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例
// 如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现
// 了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
题解
/////////////////////////////// 直接法 /////////////////////////////
// 排序,然后逐个遍历数
// 直接法无法在牛客通过
// 力扣
//
// 执行用时:3 ms, 在所有 Java 提交中击败了34.81%的用户
// 内存消耗:41.7 MB, 在所有 Java 提交中击败了59.53%的用户
class Solution {
public int majorityElement(int[] nums) {
if (nums.length == 0)
return -1;
if (nums.length == 1)
return nums[0];
Arrays.sort(nums);
int len = nums.length / 2 + 1;
int count = 1;
int i = 0;
while (i < nums.length) {
if (nums[i] != nums[i + 1])
count = 1;
else {
count++;
i++;
}
if (count >= len)
break;
}
return nums[i];
}
}
多数投票法我做了个ppt放在代码下面,感兴趣可以看看。
//////////////////////////////// 多数投票法 ////////////////////////
// 比较好的方法
// 如果某个数字符合条件,那么它出现的次数就比其他所有数字出现的次数加起来还要多。
// 具体可以看看这个 https://www.zhihu.com/question/49973163/answer/617122734
// 力扣
// 不验证的话,就是取出现次数最多的数字
// 执行用时:1 ms, 在所有 Java 提交中击败了99.99%的用户
// 内存消耗:41.9 MB, 在所有 Java 提交中击败了38.26%的用户
class Solution {
public int majorityElement(int[] nums) {
int max = nums[0];
for (int i = 1, count = 1; i < nums.length; i++) {
if (nums[i] == max)
count++;
else
count--;
if (count == 0) {
max = nums[i];
count = 1;
}
}
return max;
}
}
// 力扣
// 加上验证环节
// 执行用时:2 ms, 在所有 Java 提交中击败了60.11%的用户
// 内存消耗:41.8 MB, 在所有 Java 提交中击败了44.96%的用户
class Solution {
public int majorityElement(int[] nums) {
int max = nums[0];
for (int i = 1, count = 1; i < nums.length; i++) {
if (nums[i] == max)
count++;
else
count--;
if (count == 0) {
max = nums[i];
count = 1;
}
}
// 验证环节
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == max)
count++;
}
return count >= nums.length / 2 + 1 ? max : 0;
}
}
// 牛客
// 牛客必须要有验证环节,否则无法通过,所以牛客要力扣要严格(严谨)
// 运行时间:12ms
// 占用内存:9556k
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int max = array[0];
for (int i = 1, count = 1; i < array.length; i++) {
if (array[i] == max)
count++;
else
count--;
if (count <= 0) {
max = array[i];
count = 1;
}
}
// 验证环节
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == max)
count++;
}
return count >= array.length / 2 + 1 ? max : 0;
}
}