数组中出现次数超过一半地数字
牛客网 - 数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
- 注意 在牛客网中,超过一半的数不一定存在!!!(需要判断存在与否)
思路:
用pre记录上一次访问的值,count表明当前值出现的次数,如果下一个值和当前值相同那么count++;如果不同count–,减到0的时候就要更换新的pre值了,因为如果存在超过数组长度一半的值,那么最后pre一定会是该值。
import java.util.Arrays;
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
if(array.length == 0) return 0;
int pre = array[0];
int count = 1;
for(int i = 1; i < array.length; i++){
if(pre == array[i]){
count += 1;
}else{
count -= 1;
}
if(count == 0){
pre = array[i];
count = 1;
}
}
// pre智能保证如果存在大于一半的数,就是pre;奴能保证大于一半的条件一定存在!!!!
// 1 2 3 4 5 6 5;返回pre是5,但其实不存在大于一半的数!因为前面两两不相等的数互相抵消了~
int num = 0;
for(int i = 0; i < array.length; i++){
if(pre == array[i]) num++;
}
if(num > array.length / 2){
return pre;
}else{
return 0;
}
}
}
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if( len(numbers) == 0): return 0
pre = numbers[0];
count = 1;
for i in range(1, len(numbers)):
if (pre == numbers[i]):
count += 1
if(pre != numbers[i]):
count -= 1
if(count == 0):
pre = numbers[i]
count = 1
num = 0
for i in range(len(numbers)):
if (numbers[i] == pre):
num += 1
if num> len(numbers)/2 : return pre
return 0;
leetcode 39 or 169
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。你可以假设数组是非空的,并且给定的数组总是存在多数元素。
- leetcode 中保证了大于一半的数字一定存在,因此可以直接返回抵消后剩下的那个数~~
class Solution {
public int majorityElement(int[] nums) {
if(nums.length == 0) return 0;
int pre = nums[0];
int count = 1;
// 两两抵消判断
for(int i = 1; i < nums.length; i++){
if(pre == nums[i]){
count++;
}else{
count--;
}
if(count == 0){
pre = nums[i];
count = 1;
}
}
return pre;
}
}