题目大意

    给定一个大小为 n 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1)。

    解题思路

    代码

    1. package leetcode
    2. // 解法一 时间复杂度 O(n) 空间复杂度 O(1)
    3. func majorityElement229(nums []int) []int {
    4. // since we are checking if a num appears more than 1/3 of the time
    5. // it is only possible to have at most 2 nums (>1/3 + >1/3 = >2/3)
    6. count1, count2, candidate1, candidate2 := 0, 0, 0, 1
    7. // Select Candidates
    8. for _, num := range nums {
    9. if num == candidate1 {
    10. count1++
    11. } else if num == candidate2 {
    12. count2++
    13. } else if count1 <= 0 {
    14. // We have a bad first candidate, replace!
    15. candidate1, count1 = num, 1
    16. } else if count2 <= 0 {
    17. // We have a bad second candidate, replace!
    18. candidate2, count2 = num, 1
    19. } else {
    20. // Both candidates suck, boo!
    21. count1--
    22. count2--
    23. }
    24. }
    25. // Recount!
    26. count1, count2 = 0, 0
    27. for _, num := range nums {
    28. if num == candidate1 {
    29. count1++
    30. } else if num == candidate2 {
    31. count2++
    32. }
    33. }
    34. length := len(nums)
    35. if count1 > length/3 && count2 > length/3 {
    36. return []int{candidate1, candidate2}
    37. }
    38. if count1 > length/3 {
    39. return []int{candidate1}
    40. }
    41. if count2 > length/3 {
    42. return []int{candidate2}
    43. }
    44. return []int{}
    45. }
    46. // 解法二 时间复杂度 O(n) 空间复杂度 O(n)
    47. func majorityElement229_1(nums []int) []int {
    48. result, m := make([]int, 0), make(map[int]int)
    49. for _, val := range nums {
    50. if v, ok := m[val]; ok {
    51. m[val] = v + 1
    52. } else {
    53. m[val] = 1
    54. }
    55. }
    56. for k, v := range m {
    57. if v > len(nums)/3 {
    58. result = append(result, k)
    59. }
    60. }
    61. return result
    62. }