剑指offer 数组中出现超过一半的数字

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if(numbers.empty()){
            return 0;
        }
        if(numbers.size() == 1){
            return numbers[0];
        }
        int len = (int)numbers.size();
        float target = len/2.0;
        map<int, int> m;
        for(int num: numbers){
            if(m.count(num) != 0){
                m[num]++;
                if(m[num] > target) return num;
            }
            else{
                m.insert(pair<int, int>(num, 1));
            }
        }
        return 0;
    }
};
# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        if not numbers:
            return 0
        if len(numbers) == 1:
            return numbers[0]
        m = {}
        for num in numbers:
            if num not in m.keys():
                m[num] = 1
            else:
                m[num] += 1
            

posted @ 2018-08-30 15:05  一条图图犬  阅读(118)  评论(0编辑  收藏  举报