题解 | #数组中出现次数超过一半的数字#自己写的hash表

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

http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> nums) {
        unordered_map<int, int> hash;
        int n = nums.size();
        for(int i = 0;i < n;i++){
            if(hash.find(nums[i]) != hash.end()){
                hash[nums[i]]++;
            }
            else{
                hash[nums[i]] = 1;
            }
            if(hash[nums[i]] > n/2){
                return nums[i];
            }
        }
        return -1;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务