dengxinyi 6 лет назад
Родитель
Сommit
d01b0c15c0

+ 33 - 0
medium/378.kth-smallest-element-in-a-sorted-matrix.go

@@ -0,0 +1,33 @@
+type array [][2]int
+
+func (a array) Len() int           { return len(a) }
+func (a array) Less(i, j int) bool { return a[i][0] < a[j][0] }
+func (a array) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
+
+func (a *array) Push(x interface{}) {
+	*a = append(*a, x.([2]int))
+}
+
+func (a *array) Pop() interface{} {
+	x := (*a)[a.Len()-1]
+	*a = (*a)[:a.Len()-1]
+	return x
+}
+
+func kthSmallest(matrix [][]int, k int) int {
+	n := len(matrix)
+	idx := make([]int, n)
+	var pq array = make([][2]int, 0)
+	for i := 0; i < n; i++ {
+		heap.Push(&pq, [2]int{matrix[i][0], i})
+	}
+	for i := 0; i < k-1; i++ {
+		x := heap.Pop(&pq).([2]int)
+		idx[x[1]]++
+		if nid := idx[x[1]]; nid < n {
+			heap.Push(&pq, [2]int{matrix[x[1]][nid], x[1]})
+		}
+	}
+	return heap.Pop(&pq).([2]int)[0]
+}
+

+ 58 - 0
medium/380.insert-delete-getrandom-o1.go

@@ -0,0 +1,58 @@
+var empty struct{} = struct{}{}
+
+type RandomizedSet struct {
+	set map[int]struct{}
+	key []int
+}
+
+/** Initialize your data structure here. */
+func Constructor() RandomizedSet {
+	return RandomizedSet{
+		set: make(map[int]struct{}),
+	}
+}
+
+/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
+func (this *RandomizedSet) Insert(val int) bool {
+	if _, ok := this.set[val]; ok {
+		return false
+	}
+	this.set[val] = empty
+	this.key = append(this.key, val)
+	return true
+}
+
+/** Removes a value from the set. Returns true if the set contained the specified element. */
+func (this *RandomizedSet) Remove(val int) bool {
+	if _, ok := this.set[val]; ok {
+		delete(this.set, val)
+		if n := len(this.set); 2*n < len(this.key) {
+			this.key = make([]int, n)
+			i := 0
+			for k := range this.set {
+				this.key[i] = k
+				i++
+			}
+		}
+		return true
+	}
+	return false
+}
+
+/** Get a random element from the set. */
+func (this *RandomizedSet) GetRandom() int {
+	for {
+		val := this.key[rand.Intn(len(this.key))]
+		if _, ok := this.set[val]; ok {
+			return val
+		}
+	}
+}
+
+/**
+ * Your RandomizedSet object will be instantiated and called as such:
+ * obj := Constructor();
+ * param_1 := obj.Insert(val);
+ * param_2 := obj.Remove(val);
+ * param_3 := obj.GetRandom();
+ */