剑指offer66题--Java实现,c++实现和python实现 28.数组中出现次数超过一半的数字

题目描述

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

C++

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        int n = numbers.size();
        if (n == 0) return 0;
         
        int num = numbers[0], count = 1;
        for (int i = 1; i < n; i++) {
            if (numbers[i] == num) count++;
            else count--;
            if (count == 0) {
                num = numbers[i];
                count = 1;
            }
        }
        // Verifying
        count = 0;
        for (int i = 0; i < n; i++) {
            if (numbers[i] == num) count++;
        }
        if (count * 2 > n) return num;
        return 0;
    }
};

JAVA

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        int target = array[array.length/2];
        int n = 0;
        for(int i=0;i<array.length;i++){
            if(array[i]==target)
                n++;
        }
        if(n>array.length/2)
            return target;
        return 0;
    }
}

Python

# -*- coding:utf-8 -*-
from collections import Counter
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        if not numbers: return 0
        res = 0
        times = 0
        for i, num in enumerate(numbers):
            if times == 0:
                res = num
                times = 1
            elif num == res:
                times += 1
            else:
                times -= 1
        return res if numbers.count(res) > len(numbers) / 2 else 0

猜你喜欢

转载自blog.csdn.net/walter7/article/details/85334363
今日推荐