共计 1219 个字符,预计需要花费 4 分钟才能阅读完成。
第一题 打乱数组
题目信息
解题思路
代码
package main
import "math/rand"
//leetcode submit region begin(Prohibit modification and deletion)
type Solution struct {nums,original []int
}
func Constructor(nums []int) Solution {return Solution{nums,append([]int(nil),nums...)}
}
func (this *Solution) Reset() []int {copy(this.nums,this.original)
return this.nums
}
func (this *Solution) Shuffle() []int {n:=len(this.nums)
for i:=range this.nums{j:=i+rand.Intn(n-i)
this.nums[i], this.nums[j] = this.nums[j], this.nums[i]
}
return this.nums
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.Reset();
* param_2 := obj.Shuffle();
*/
//leetcode submit region end(Prohibit modification and deletion)
第二题
题目信息
解题思路
代码
type MinStack struct {stack []int
minStack []int}
func Constructor() MinStack {
return MinStack{[]int{},
[]int{math.MaxInt64},
}
}
func (this *MinStack) Push(x int) {this.stack = append(this.stack, x)
top := this.minStack[len(this.minStack)-1]
this.minStack = append(this.minStack, min(x, top))
}
func (this *MinStack) Pop() {this.stack = this.stack[:len(this.stack)-1]
this.minStack = this.minStack[:len(this.minStack)-1]
}
func (this *MinStack) Top() int {return this.stack[len(this.stack)-1]
}
func (this *MinStack) GetMin() int {return this.minStack[len(this.minStack)-1]
}
func min(x, y int) int {
if x < y {return x}
return y
}
正文完