一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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.

(二)解题

题目大意:找出数组中出现次数超过一般的数

解题思路:

最简单的就是首先对数组进行排序,然后中间的那个数就是出现次数超过一半的数。



class Solution {

public:

    int majorityElement(vector<int>& nums) {

        int len = nums.size();

        sort(nums.begin(),nums.end());//调用STL的排序函数

        return nums[len/2];

    }

};

另一种优化的算法。O(n)复杂度。

定义两个整数j和num,j记录次数,num记录一个数

当遍历到nums数组的下一个数时,如果nums[j]==num,或者j==0,此时j++,并保存num的值为nums[j],

如果j!=0且nums[j]!=num,这时候j–,由于num这个数出现次数超过一半,那么最后一个将j变成1的数就是我们要找的数。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int j = 0;//记录次数
        int ret = nums[0];//初始化为第一个数
        int size = nums.size();
        for(int i =0 ; i < size ; i++)
        {
            if(j==0||nums[i]== ret){
                ret=nums[i];
                j++;
            }
            else j--;
        }
        return ret;
    }
};

最新文章

  1. CSharpGL(31)[译]OpenGL渲染管道那些事
  2. 发出HTTP请求并获得HTTP响应
  3. js中的cookie操作
  4. 4.1HTML和Bootstrap css精华
  5. Excel 函数记录
  6. 【英语】Bingo口语笔记(58) - blow系列
  7. 在centos中使用vim编辑器
  8. 解析 .Net Core 注入 (3) 创建对象
  9. Jquery基础知识01
  10. DP入门
  11. 永久开启完整版Google Play
  12. Codeforces Round #533 (Div. 2) C.思维dp D. 多源BFS
  13. 流媒体Red5服务自定义媒体文件路径
  14. 批量备份H3C交换机路由器配置
  15. C# 获取文件名、目录、后缀、无后缀文件名、扩展名、根目录等
  16. BG.Hadoop.Master
  17. 高可用OpenStack(Queen版)集群-7.Neutron控制/网络节点集群
  18. WebAPI请求(转)
  19. windows 下 openssl 生成RSA私钥公钥以及PKCS8
  20. JAVA实现图的邻接表以及DFS

热门文章

  1. SpringCloud学习之Zuul统一异常处理及回退
  2. Xamarin开发缺少的android_m2repository_rxx.zip下载地址以及MD5
  3. JavaBean toString方式
  4. Redis学习汇总
  5. hadoop hdfs 高可用
  6. 微信小程序 --- 无法跳转到tab页面问题
  7. Sprk SQL
  8. Docker的名字空间
  9. Java内存泄漏分析系列之二:jstack生成的Thread Dump日志结构解析
  10. ASP.NET实现在线浏览Word文档另一种解决方案(Word转PDF)