首页 > 其他 > 详细

【LeetCode】169. Majority Element 解题小结

时间:2016-08-23 14:30:37      阅读:160      评论:0      收藏:0      [点我收藏+]

题目:Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Credits:

自己的思路大概是建立一个map,key对应数字,value对应数字出现的次数,然后比较次数最多的那个应该就是Majority Element。

class Solution {
public:
    unordered_map<int, int> map;
    int majorityElement(vector<int>& nums) {
    int indexMax;
        for (int i = 0; i < nums.size(); i++) {
            if (map.find(nums[i]) == map.end()) {
                map[nums[i]] = 1;
            }
            else {
                map[nums[i]]++;
            }
        }
        indexMax = 0;
        for (int i = 1; i < nums.size(); i++) {
            if (map[nums[i]] > map[nums[indexMax]] && map[nums[i]] >= map.size() / 2)
                indexMax = i;
        }
        return nums[indexMax];
    }
};

 

【LeetCode】169. Majority Element 解题小结

原文:http://www.cnblogs.com/Doctengineer/p/5798955.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!