dengxinyi 6 anos atrás
pai
commit
c642fd3e4c
2 arquivos alterados com 89 adições e 0 exclusões
  1. 32 0
      medium/382.linked-list-random-node.go
  2. 57 0
      medium/384.shuffle-an-array.go

+ 32 - 0
medium/382.linked-list-random-node.go

@@ -0,0 +1,32 @@
+/**
+ * Definition for singly-linked list.
+ * type ListNode struct {
+ *     Val int
+ *     Next *ListNode
+ * }
+ */
+type Solution struct {
+	arr []int
+	n   int
+}
+
+/** @param head The linked list's head.
+  Note that the head is guaranteed to be not null, so it contains at least one node. */
+func Constructor(head *ListNode) (sol Solution) {
+	for curr := head; curr != nil; curr = curr.Next {
+		sol.arr = append(sol.arr, curr.Val)
+		sol.n++
+	}
+	return
+}
+
+/** Returns a random node's value. */
+func (this *Solution) GetRandom() int {
+	return this.arr[rand.Intn(this.n)]
+}
+
+/**
+ * Your Solution object will be instantiated and called as such:
+ * obj := Constructor(head);
+ * param_1 := obj.GetRandom();
+ */

+ 57 - 0
medium/384.shuffle-an-array.go

@@ -0,0 +1,57 @@
+//package main
+
+//import (
+//	"fmt"
+//	"math/rand"
+//)
+
+type Solution struct {
+	arr []int
+	sol []int
+}
+
+func Constructor(nums []int) Solution {
+	solution := Solution{arr: nums}
+	solution.sol = make([]int, len(nums))
+	copy(solution.sol, nums)
+	return solution
+}
+
+/** Resets the array to its original configuration and return it. */
+func (this *Solution) Reset() []int {
+	copy(this.sol, this.arr)
+	return this.arr
+}
+
+/** Returns a random shuffling of the array. */
+func (this *Solution) Shuffle() []int {
+	n := len(this.arr)
+	for i := 0; i < n; i++ {
+		j := i + rand.Intn(n-i)
+		this.sol[i], this.sol[j] = this.sol[j], this.sol[i]
+	}
+	return this.sol
+}
+
+//type tuple3 struct {
+//	_1 int
+//	_2 int
+//	_3 int
+//}
+
+//func main() {
+//	sol := Constructor([]int{1, 2, 3})
+//	m := make(map[tuple3]int)
+//	for i := 0; i < 10000; i++ {
+//		arr := sol.Shuffle()
+//		m[tuple3{arr[0], arr[1], arr[2]}]++
+//	}
+//	fmt.Println(m)
+//}
+
+/**
+ * Your Solution object will be instantiated and called as such:
+ * obj := Constructor(nums);
+ * param_1 := obj.Reset();
+ * param_2 := obj.Shuffle();
+ */