邓心一 6 years ago
parent
commit
abe192f720
1 changed files with 35 additions and 0 deletions
  1. 35 0
      medium/229.majority-element-ii.go

+ 35 - 0
medium/229.majority-element-ii.go

@@ -0,0 +1,35 @@
+func majorityElement(nums []int) (ans []int) {
+	n1, n2, c1, c2 := 0, 0, 0, 0
+	for _, n := range nums { // At most 2 majority elements occur more than n/3 times.
+	// Use two counters to vote the occurence of the numbers.
+		switch {
+		case n == n1:
+			c1++
+		case n == n2:
+			c2++
+		case c1 == 0:
+			n1, c1 = n, 1
+		case c2 == 0:
+			n2, c2 = n, 1
+		default:
+			c1, c2 = c1-1, c2-1
+		}
+	}
+	c1, c2 = 0, 0
+	for _, n := range nums {
+		switch n {
+		case n1:
+			c1++
+		case n2:
+			c2++
+		}
+	}
+	if len(nums)/3 < c1 {
+		ans = append(ans, n1)
+	}
+	if len(nums)/3 < c2 {
+		ans = append(ans, n2)
+	}
+	return
+}
+