229.majority-element-ii.go 596 B

1234567891011121314151617181920212223242526272829303132333435
  1. func majorityElement(nums []int) (ans []int) {
  2. n1, n2, c1, c2 := 0, 0, 0, 0
  3. for _, n := range nums { // At most 2 majority elements occur more than n/3 times.
  4. // Use two counters to vote the occurence of the numbers.
  5. switch {
  6. case n == n1:
  7. c1++
  8. case n == n2:
  9. c2++
  10. case c1 == 0:
  11. n1, c1 = n, 1
  12. case c2 == 0:
  13. n2, c2 = n, 1
  14. default:
  15. c1, c2 = c1-1, c2-1
  16. }
  17. }
  18. c1, c2 = 0, 0
  19. for _, n := range nums {
  20. switch n {
  21. case n1:
  22. c1++
  23. case n2:
  24. c2++
  25. }
  26. }
  27. if len(nums)/3 < c1 {
  28. ans = append(ans, n1)
  29. }
  30. if len(nums)/3 < c2 {
  31. ans = append(ans, n2)
  32. }
  33. return
  34. }