如何找到数组中出现次数超过一半的数字
题目描述:
【LeetCode】面试题39. 数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:时间复杂度O(nlogn)
思路:
将数组排序,中间的那个数一定是出现次数都多于其他的数的那个数
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return(nums[nums.length/2]);
}
方法二:时间复杂度O(n)
思路:
既然有一个数出现的次数比其他数出现的次数都多。
我们在遍历数组的时候保存两个值:一个是数组中的一个数字;另一个是次数
当遍历到下一个数的时候,是不同的数,那么次数减一,如果相同,次数加一
如果减到了0,换成这个新的数,次数设置为1
代码如下:
public int majorityElement(int[] nums) {
int num = nums[0];
int times = 0;
for(int i = 0; i< nums.length; i++){
if(nums[i] == num){
times ++;
}else{
times --;
if(times == 0){
num = nums[i];
times = 1;
}
}
}
return num;
}