zoukankan      html  css  js  c++  java
  • 剑指offer--11.数组中出现次数超过一半的数字

    unique(), count()函数好用

    ----------------------------------------------------------------------

    时间限制:1秒 空间限制:32768K 热度指数:290021
    本题知识点: 数组

    题目描述

    数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
    class Solution {
    public:
        int MoreThanHalfNum_Solution(vector<int> numbers) {
            vector<int> vec(numbers.begin(), numbers.end());
            int len = unique(vec.begin(), vec.end())-vec.begin();
            for (auto it = vec.begin(); it != vec.end(); it++) {
                if (count(numbers.begin(), numbers.end(), *(it)) > numbers.size()/2)  {
                    return *(it);
                }
            }
            return 0;
        }
    };
  • 相关阅读:
    hw4 打卡
    lab4打卡
    hw3打卡
    lab3打卡
    hw2打卡
    lab2打卡
    hw1打卡
    Java Trie(词典树)实现
    Java HashMap实现
    DFS习题复习(2) DFS的实际应用:括号检测,graph Bipartite及随机生成迷宫
  • 原文地址:https://www.cnblogs.com/slothrbk/p/10563781.html
Copyright © 2011-2022 走看看