剑指offer39_数组中出现次数超过一半的数字(java)

数组中出现次数超过一半地数字

牛客网 - 数组中出现次数超过一半的数字

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值