找出向量中出现最多的数字

时间:2010-03-21 22:08:31

标签: c++ vector

我有一些数字存储在矢量中。我想找出矢量中出现最多的数字。

是否有任何简单/快速算法(STL或其他)可以做到这一点?

6 个答案:

答案 0 :(得分:6)

对它进行排序,然后遍历它并保留一个当前数字与前一个数字相同时递增的计数器,否则重置为0。还要跟踪到目前为止计数器的最高值是什么,以及达到该值时的当前数字。此解决方案为O(n log n)(因为排序)。

或者,您可以使用从int到int的散列映射(或者如果您知道数字在有限范围内,您可以只使用数组)并迭代向量,每个数字将the_hashmap[current_number]增加1 。然后遍历hashmap以找到其最大值(以及属于它的键)。这需要一个hashmap数据结构(除非你可以使用也会更快的数组),这不是STL的一部分。

答案 1 :(得分:4)

如果您想避免对矢量v进行排序,请使用地图:

int max = 0;
int most_common = -1;
map<int,int> m;
for (vi = v.begin(); vi != v.end(); vi++) {
  m[*vi]++;
  if (m[*vi] > max) {
    max = m[*vi]; 
    most_common = *vi;
  }
}

这需要更多内存并且具有非常相似的预期运行时间。所需的内存应该是完整的矢量副本的顺序,如果有许多重复的条目,则更少。

答案 2 :(得分:0)

我就这样做了:

    int max=0,mostvalue=a[0];
    for(i=0;i<a.size();i++)
    {
        co = (int)count(a.begin(), a.end(), a[i]);
        if(co > max)
        {       max = co;
                mostvalue = a[i];
        }
    }

我只是不知道它有多快,即O()?如果有人可以计算并在此处发布,那就没问题了。

答案 3 :(得分:0)

这是一个O(n)通用解决方案,用于查找迭代器范围中最常见的元素。您只需执行以下操作即可使用它:

int commonest = most_common(my_vector.begin(), my_vector.end());

使用iterator_traits<>从迭代器中提取值类型。

template<class InputIt, class T = typename std::iterator_traits<InputIt>::value_type>
T most_common(InputIt begin, InputIt end)
{
    std::map<T, int> counts;
    for (InputIt it = begin; it != end; ++it) {
        if (counts.find(*it) != counts.end()) {
            ++counts[*it];
        }
        else {
            counts[*it] = 1;
        }
    }
    return std::max_element(counts.begin(), counts.end(),
            [] (const std::pair<T, int>& pair1, const std::pair<T, int>& pair2) {
            return pair1.second < pair2.second;})->first;
}

答案 4 :(得分:0)

尝试一下

Caused by: java.lang.IllegalArgumentException: Can't encode class java.util.HashMap to json

2019-04-02 18:09:26,835 12247 [qtp1750286943-20] ERROR c.v.flow.router.InternalServerError - There was an exception while trying to navigate to 'redir'
java.lang.IllegalArgumentException: Unable to create an instance of 'myproject.view.RedirectForm'. The constructor threw an exception.
    at com.vaadin.flow.internal.ReflectTools.createProxyInstance(ReflectTools.java:510)
    at com.vaadin.flow.internal.ReflectTools.createInstance(ReflectTools.java:447)
    at com.vaadin.flow.di.DefaultInstantiator.getOrCreate(DefaultInstantiator.java:65)
    at com.vaadin.flow.di.Instantiator.createRouteTarget(Instantiator.java:158)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.lambda$getRouteTarget$1(AbstractNavigationStateRenderer.java:121)
    at java.util.Optional.orElseGet(Optional.java:267)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.getRouteTarget(AbstractNavigationStateRenderer.java:120)
    at com.vaadin.flow.router.internal.AbstractNavigationStateRenderer.handle(AbstractNavigationStateRenderer.java:178)
    at com.vaadin.flow.router.Router.handleNavigation(Router.java:219)
    at com.vaadin.flow.router.Router.navigate(Router.java:190)
    at com.vaadin.flow.router.Router.initializeUI(Router.java:92)
    at com.vaadin.flow.server.BootstrapHandler.createAndInitUI(BootstrapHandler.java:1117)
    at com.vaadin.flow.server.BootstrapHandler.synchronizedHandleRequest(BootstrapHandler.java:396)
    at com.vaadin.flow.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:40)
    at com.vaadin.flow.server.VaadinService.handleRequest(VaadinService.java:1507)
    at com.vaadin.flow.server.VaadinServlet.service(VaadinServlet.java:242)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:867)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1623)
    at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:214)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:540)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1588)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1345)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1557)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1247)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)
    at org.eclipse.jetty.server.handler.HandlerList.handle(HandlerList.java:61)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    at org.eclipse.jetty.server.Server.handle(Server.java:502)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:364)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:260)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
    at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:118)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException: null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.vaadin.flow.internal.ReflectTools.createProxyInstance(ReflectTools.java:479)
    ... 45 common frames omitted
Caused by: java.lang.IllegalArgumentException: Can't encode class java.util.HashMap to json
    at com.vaadin.flow.internal.JsonCodec.encodeWithoutTypeInfo(JsonCodec.java:165)
    at com.vaadin.flow.internal.JsonCodec.encodeWithTypeInfo(JsonCodec.java:80)
    at com.vaadin.flow.component.page.Page.executeJavaScript(Page.java:338)
    at myproject.view.RedirectForm.<init>(RedirectView.kt:29)
    ... 50 common frames omitted

答案 5 :(得分:-1)

您可以使用以下代码:

vector <int> v;
    // add some elements
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(1);

    int maxCount = 0, mostElement = *(v.begin());
    int sz = v.size(); // to avoid calculating the size every time
    for(int i=0; i < sz; i++)
    {
        int c = count(v.begin(), v.end(), v.at(i));
        if(c > maxCount)
        {   maxCount = c;
            mostElement = v.at(i);
        }
    }
    cout << "the number appeared the most is " << mostElement <<"\n";
    cout << "it appered " <<maxCount<<" times";

注意:如果向量的大小不能由整数保持,则可以使用以下for循环来避免任何迭代器溢出:

    for(auto it= v.begin(); it != v.end(); it++)
    {
        int c = count(v.begin(), v.end(), *it);
        if(c > maxCount)
        {   maxCount = c;
            mostElement = *it;
        }
    }