LeetCode169. Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. (Easy)

You may assume that the array is non-empty and the majority element always exist in the array.

分析:

抵消的思想,维护一个result和count,与result相同则count++,否则count--,到0时更新result的值,由于主元素个数较多,所有最后一定能留下。

代码:

  1. class Solution {
  2. public:
  3. int majorityElement(vector<int>& nums) {
  4. int result = ;
  5. int count = ;
  6. for (int i = ; i < nums.size(); ++i) {
  7. if (nums[i] == result && count != ) {
  8. count++;
  9. }
  10. else if (count == ) {
  11. result = nums[i];
  12. count = ;
  13. }
  14. else {
  15. count--;
  16. }
  17. }
  18. return result;
  19. }
  20. };

LintCode47. Majority NumberII

Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array. (Medium)

Find it.

Notice : There is only one majority number in the array.

分析:

同majority number1的思路相似,维护两个result和count,相同则对相应count操作,不同则均减一;

注意最后剩下两个元素,并不一定count值大的就一定是出现次数多的(可能另一个参与抵消过多),所以需要重新遍历一遍,对这个两个数比较出现次数大小。

代码:

  1. class Solution {
  2. public:
  3. /**
  4. * @param nums: A list of integers
  5. * @return: The majority number occurs more than 1/3.
  6. */
  7. int majorityNumber(vector<int> nums) {
  8. // write your code here
  9. int candidate1 = , candidate2 = ;
  10. int count1 = , count2 = ;
  11. for (int i = ; i < nums.size(); ++i) {
  12. if (nums[i] == candidate1 && count1 != ) {
  13. count1++;
  14. }
  15. else if (nums[i] == candidate2 && count2 != ) {
  16. count2++;
  17. }
  18. else if (count1 == ) {
  19. candidate1 = nums[i];
  20. count1 = ;
  21. }
  22. else if (count2 == ) {
  23. candidate2 = nums[i];
  24. count2 = ;
  25. }
  26. else {
  27. count1--;
  28. count2--;
  29. }
  30. }
  31. count1 = ;
  32. count2 = ;
  33. for (int i = ; i < nums.size(); ++i) {
  34. if (nums[i] == candidate1) {
  35. count1++;
  36. }
  37. else if (nums[i] == candidate2) {
  38. count2++;
  39. }
  40. }
  41. return count1 > count2 ? candidate1 : candidate2;
  42. }
  43. };

LeetCode229. Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.(Medium)

分析:

这个与lintcode中的majority number2基本相似,只是要求找到所有的大于n / 3次的元素(至多也就是两个);

所以最后一步从比较两个canditate的count大小,变成将这两个count与 size() / 3比较。

代码:

  1. class Solution {
  2. public:
  3. vector<int> majorityElement(vector<int>& nums) {
  4. int candidate1 = , candidate2 = ;
  5. int count1 = , count2 = ;
  6. for (int i = ; i < nums.size(); ++i) {
  7. if (nums[i] == candidate1 && count1 != ) {
  8. count1++;
  9. }
  10. else if (nums[i] == candidate2 && count2 != ) {
  11. count2++;
  12. }
  13. else if (count1 == ) {
  14. candidate1 = nums[i];
  15. count1 = ;
  16. }
  17. else if (count2 == ) {
  18. candidate2 = nums[i];
  19. count2 = ;
  20. }
  21. else {
  22. count1--;
  23. count2--;
  24. }
  25. }
  26. count1 = ;
  27. count2 = ;
  28. for (int i = ; i < nums.size(); ++i) {
  29. if (nums[i] == candidate1) {
  30. count1++;
  31. }
  32. else if (nums[i] == candidate2) {
  33. count2++;
  34. }
  35. }
  36. vector<int> result;
  37. if (count1 > nums.size() / ) {
  38. result.push_back(candidate1);
  39. }
  40. if (count2 > nums.size() / ) {
  41. result.push_back(candidate2);
  42. }
  43. return result;
  44.  
  45. }
  46. };

LintCode48. Majority Number III

Given an array of integers and a number k, the majority number is the number that occurs more than 1/k of the size of the array. (Medium)

Find it.

Notice:There is only one majority number in the array.

分析:

从前一题的1/3变为1/k,道理还是一样,不过这次需要用一个hashmap来维护出现的次数,注意unordered_map插入删除相关操作的写法即可。

尤其hashmap元素个数等于k需要删除的时候,需要维护一个vector存key,如果用iterator边走边删除可能出现位置变化。

代码:

  1. class Solution {
  2. public:
  3. /**
  4. * @param nums: A list of integers
  5. * @param k: As described
  6. * @return: The majority number
  7. */
  8. int majorityNumber(vector<int> nums, int k) {
  9. // write your code here
  10. unordered_map<int, int> hash;
  11. for (int i = ; i < nums.size(); ++i) {
  12. if (hash.size() < k) {
  13. hash[nums[i]]++;
  14. }
  15. else {
  16. vector<int> eraseVec;
  17. for (auto itr = hash.begin(); itr != hash.end(); ++itr) {
  18. (itr -> second)--;
  19. if (itr -> second == ) {
  20. eraseVec.push_back(itr -> first);
  21. }
  22. }
  23. for (int i = ; i < eraseVec.size(); ++i) {
  24. hash.erase(eraseVec[i]);
  25. }
  26. hash[nums[i]]++;
  27. }
  28. }
  29. for (auto& n : hash) {
  30. n.second = ;
  31. }
  32. for (int i = ; i < nums.size(); ++i) {
  33. if (hash.find(nums[i]) != hash.end()) {
  34. hash[nums[i]]++;
  35. if (hash[nums[i]] > nums.size() / k) {
  36. return nums[i];
  37. }
  38. }
  39. }
  40. return -;
  41. }
  42. };

LeetCode169 Majority Element, LintCode47 Majority Number II, LeetCode229 Majority Element II, LintCode48 Majority Number III的更多相关文章

  1. [Swift]LeetCode503. 下一个更大元素 II | Next Greater Element II

    Given a circular array (the next element of the last element is the first element of the array), pri ...

  2. [LeetCode] 305. Number of Islands II 岛屿的数量 II

    A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand oper ...

  3. lintcode 中等题:N Queens II N皇后问题 II

    题目: N皇后问题 II 根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局. 样例 比如n=4,存在2种解决方案 解题: 和上一题差不多,这里只是求数量,这个题目定义全局变量,递 ...

  4. HDU 3567 Eight II(八数码 II)

    HDU 3567 Eight II(八数码 II) /65536 K (Java/Others)   Problem Description - 题目描述 Eight-puzzle, which is ...

  5. DE1-SOC开发板上搭建NIOS II处理器运行UCOS II

    DE1-SOC开发板上搭建NIOS II处理器运行UCOS II   今天在DE1-SOC的开发板上搭建NIOS II软核运行了UCOS II,整个开发过程比较繁琐,稍微有一步做的不对,就会导致整个过 ...

  6. 杨辉三角形II(Pascal's Triangle II)

    杨辉三角形II(Pascal's Triangle II) 问题 给出一个索引k,返回杨辉三角形的第k行. 例如,给出k = 3,返回[1, 3, 3, 1] 注意: 你可以优化你的算法使之只使用O( ...

  7. [Swift]LeetCode407. 接雨水 II | Trapping Rain Water II

    Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...

  8. 【LeetCode-面试算法经典-Java实现】【059-Spiral Matrix II(螺旋矩阵II)】

    [059-Spiral Matrix II(螺旋矩阵II)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given an integer n, generate a ...

  9. Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)

    Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...

随机推荐

  1. Gym 100712H

    Gym 100712Hhttps://vjudge.net/problem/195715/origin先缩点,再建立新图,然后跑两遍dfs求树上最长路 #include<iostream> ...

  2. Gartner首推机密计算:阿里云名列其中

    近日,全球信息技术研究机构Gartner发布了2019年云安全技术成熟度曲线报告(Gartner, Hype Cycle for Cloud Security, 2019, Jay Heiser, S ...

  3. jq 实现头像(气泡式浮动)

    前提:假设每个头像都装在li中. function headMove() { $('li').each(function () { var myLeft = Math.floor(Math.rando ...

  4. Java 线程池 +生产者消费者+MySQL读取300 万条数据

    1.1需求 数据库300 万条用户数据 ,遍历获取所有用户, 各种组合关联, 获取到一个新的json ,存到redis 上. 1.2 难点 数据库比较多, 不可能单线程查询所有的数据到内存. 1.3解 ...

  5. 使用Tomcat过程中的常见问题

    1.点击startup.bat,启动Tomcat     DOS弹窗一闪而过 鼠标选中startup.bat这个文件,右键选择“编辑“,在末尾添加        pause

  6. [Day4] Nginx Http模块二

    一. POST_READ阶段     1. 用户ip在http请求中的传递? 前提:Tcp连接四元组(src ip,src port,dst ip,dst port) HTTP头部 X-Formard ...

  7. 2019.10.26 csp-s模拟测试88 反思总结

    今天的主人公是什么? 60.1K!!!! 先扔代码再更新防止我等会儿一上头不打算写完题解 T1: #include<iostream> #include<cstdio> #in ...

  8. StopWatch 监控Java代码运行时间和分析性能

    背景 有时我们在做开发的时候需要记录每个任务执行时间,或者记录一段代码执行时间,最简单的方法就是打印当前时间与执行完时间的差值,然后这样如果执行大量测试的话就很麻烦,并且不直观,如果想对执行的时间做进 ...

  9. kuangbin带我飞QAQ 最短路

    1. poj 1502 Mathches Game 裸最短路 #include <iostream> #include <string.h> #include <cstd ...

  10. Effective Modern C++  条款1:理解模板型别推导

    成百上千的程序员都在向函数模板传递实参,并拿到了完全满意的结果,而这些程序员中却有很多对这些函数使用的型别是如何被推导出的过程连最模糊的描述都讲不出来. 但是当模板型别推导规则应用于auto语境时,它 ...