美文网首页
229. Majority Element II

229. Majority Element II

作者: jluemmmm | 来源:发表于2021-10-17 15:40 被阅读0次

给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。

摩尔投票法

大于 n/3 的数最多有三个

  • 时间复杂度O(n),空间复杂度O(1)
  • Runtime: 72 ms, faster than 97.23%
  • Memory Usage: 42.3 MB, less than 20.16%
/**
 * @param {number[]} nums
 * @return {number[]}
 */
var majorityElement = function(nums) {
  let count1 = 0;
  let count2 = 0;
  let candidate1;
  let candidate2;
  
  for (let val of nums) {
    if (candidate1 === val) {
      count1++;
    } else if (candidate2 === val) {
      count2++;
    } else if (count1 === 0) {
      candidate1 = val;
      count1++;
    } else if (count2 === 0) {
      candidate2 = val;
      count2++;
    } else {
      count1--;
      count2--;
    }
  }
  
  count1 = 0;
  count2 = 0;
  for (let val of nums) {
    if (candidate1 === val) {
      count1++;
    }
    if (candidate2 === val) {
      count2++;
    }
  }
  
  const res = [];
  const len = parseInt(nums.length / 3);
  if (count1 > len) res.push(candidate1)
  if (count2 > len) res.push(candidate2);
  return res;
};

相关文章

  • II Boyer-Moore Majority Vote Alg

    229. Majority Element II Given an integer array of size n...

  • 229. Majority Element II

    先排序 然后顺序扫描,需要注意边缘,代码如下: 但是这道题目限制了时间是限行时间空间是o(1),因此,既不能使用排...

  • 229. Majority Element II

    Given an integer array of size n, find all elements that ...

  • 229. Majority Element II

    题目 题目很简短,给定一个包含n个数字的数组,找出所有出现次数超过 ⌊ n/3 ⌋ 次的数。要求O(n)时间复杂度...

  • 229. Majority Element II

    思路就是三个三个删,如何描述是三个三个删的关键是两个count要描述好。之前没仔细写,count应该有四种case...

  • 229. Majority Element II

    Question Given an integer array of size n, find all eleme...

  • 229. Majority Element II

    https://leetcode.com/problems/majority-element-ii/ 给定一个数组...

  • 229. Majority Element II

    给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 摩尔投票法 大于 n/3 的数最...

  • 229. Majority Element II (M)

    Given an integer array of size n, find all elements that ...

  • Majority Element II

    Majority Element II 今天是一到有关数学计算的题目,是Majority Element(回复01...

网友评论

      本文标题:229. Majority Element II

      本文链接:https://www.haomeiwen.com/subject/roxwoltx.html