LeetCode刷算法题 - 169. Majority Element

写在前面:

程序员分两种,会算法的程序员和不会算法的程序员。几乎没有一个一线互联网公司招聘任何类别的技术人员是不考算法的,程序猿们都懂的,现在最权威流行的刷题平台就是 LeetCode。

LeetCode原题链接

string - C++ Reference

C++中int与string的相互转换

C++ Map常见用法说明

Question:

Difficulty:Easy Tag:Array

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.

Example:

Input: [3,2,3]
Output: 3
Input: [2,2,1,1,1,2,2]
Output: 2

Solution:

以下代码皆是本人用 C++写的,觉得还不错的话别忘了点个赞哦。各位同学们如果有其他更高效解题思路还请不吝赐教,多多学习。

A1、运用哈希特性
  • 运用哈希map 的不重复性质循环遍历数组
  • 以数组元素为 keyvalue 为 相同数字key 的个数
  • 当统计出value>n/2,此时 元素key 为众数。

算法时间复杂度 O(n),Runtime: 16 ms,代码如下

int x=[](){
    std::ios::sync_with_stdio(false);  //关闭STDIN和CIN同步 减少CIN读入的时间,可以减少50%以上。
    cin.tie(NULL);
    return 0;
}();

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int,int> map;
        
        for (int i=0; i<nums.size(); i++) {
            int key = nums[i];
            if (map.find(key) == map.end()) {
                map[key] = 1;
            } else{
                map[key] = map[key]+1;
            }
            if (map[key] > nums.size()/2) {
                return nums[i];
            }
        }
        return 0;
    }
};
A2、渐进排除式解法
  • 突出运用众数个数大于 n/2的特征
  • 众数个数 - 其他所有数个数 > 0
  • 换句话 任意一个数个数 - 其他所有数个数 < 0
  • 则此数排除,剩下的就是众数

算法时间复杂度 O(n),Runtime: 10 ms,代码如下

int x=[](){
    std::ios::sync_with_stdio(false);  //关闭STDIN和CIN同步 减少CIN读入的时间,可以减少50%以上。
    cin.tie(NULL);
    return 0;
}();

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int majorIndex = 0, cnt = 1;
        for(int i=0; i<nums.size(); ++i) {
            if(nums[majorIndex] == nums[i])
                cnt++;
            else
                cnt--;
            
            if(cnt==0) {
                majorIndex = i;
                cnt = 1;
            }
        }
        return nums[majorIndex];

    }
};

引用相关

LeetCode 官网

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,490评论 0 10
  • 上一节,我们创建了一个scrapy项目,下面剪短的介绍一下scrapy的结构,并着手编写一个小爬虫! 小爬虫:ht...
    海贼王_浩阅读 716评论 0 4
  • 今天做的。 1.日常平台项目的维护,包括,信息的输入,调整,以及审核。 2.和中诚天下公众号,掌控者达成推广协议。...
    poligy阅读 189评论 0 0
  • 不负春光 ——2016-2017君子兰班下学期第六封信 亲爱的大君子们和小君子们: 周末愉快! 周六的清晨,5点半...
    河南麦子的书写阅读 536评论 1 0