leetcode刷题笔记 229题 求众数II
leetcode刷题笔记 229题 求众数II
源地址:229. 求众数 II
问题描述:
给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。
进阶:尝试设计时间复杂度为 O(n)、空间复杂度为 O(1)的算法解决此问题。
示例 1:
输入:[3,2,3]
输出:[3]
示例 2:输入:nums = [1]
输出:[1]
示例 3:输入:[1,1,1,3,3,2,2,2]
输出:[1,2]提示:
1 <= nums.length <= 5 * 104
-109 <= nums[i] <= 109
//思想基于169题的摩尔投票算法
//可推广至N/K次元素,即构建K-1个候选人
object Solution {
def majorityElement(nums: Array[Int]): List[Int] = {
var cand1 = nums(0)
var cand2 = nums(0)
var count1 = 0
var count2 = 0
var res = new scala.collection.mutable.ListBuffer[Int]()
for (i <- 0 to nums.length-1) {
if (cand1 == nums(i)) {
count1 += 1
} else {
if (cand2 == nums(i)) {
count2 += 1
} else {
if (count1 == 0){
cand1 = nums(i)
count1 += 1
} else if (count2 == 0){
cand2 = nums(i)
count2 += 1
} else {
count1 -= 1
count2 -= 1
}
}
}
//println("-------"+ i +"--------")
//println(cand1)
//println(cand2)
}
count1 = 0
count2 = 0
for (num <- nums) {
if (num == cand1) count1 += 1
if (num == cand2) count2 += 1
}
if (count1 > nums.length/3) res.append(cand1)
if (cand1 != cand2 && count2 > nums.length/3) res.append(cand2)
return res.toList
}
}