练习题 (二)

 题目:

Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

我的解答:

class Solution:
    # @param {integer[]} nums
    # @return {integer[]}
    def majorityElement(self, nums):
        dicts = {}
        result = [];
        for num in nums:
            if num in dicts:
                dicts[num] += 1
            else:
                dicts[num] = 1

        for dict in dicts:
            if dicts[dict] > len(nums) / 3:
                result.append(dict)

        return result

心得:

这题的数据结构要选择Hash表之类的。但是我开始做了一个Hash-Map的C++版本,但是好像在线不好导入Hash-Map库。又想做个javascript版本的,又没有现成的内建函数。

只好选择Ruby或者Python版本的,其实我个人是喜欢Ruby语言的,但是手头没有Ruby书,很多函数都忘记差不多了,只有先写个Python版本的,实际上只有这么几行就够了。

原文地址:https://www.cnblogs.com/ender-cd/p/4608260.html