funcremoveElement(nums []int, val int)int { var low int for i, v := range nums{ if v != val{ nums[low], nums[i] = nums[i], nums[low] low++ } } return low }
funcremoveDuplicates(nums []int)int { iflen(nums) == 1{ returnlen(nums) } var low int for i, v := range nums{ if v != nums[low]{ low++ nums[low], nums[i] = nums[i], nums[low] } } return low + 1 }
funcmajorityElement(nums []int)int { var m = make(map[int]int) var k = len(nums) / 2 for _, v := range nums{ m[v]++ if m[v] > k{ return v } } return0 }
funcmaxProfit(prices []int)int { // 维护一个双端队列 var s []int var ans int for i := len(prices) - 1; i >= 0; i--{ forlen(s) > 0 && s[len(s) - 1] < prices[i]{ s = s[:len(s) - 1] } iflen(s) > 0{ // 队内有元素,与对头最大的那个进行比较 ans = max(ans, s[0] - prices[i]) } s = append(s, prices[i]) } return ans }
funcmax(x, y int)int { if x < y{ return y } return x }
funccanJump(nums []int)bool { iflen(nums) == 1{ returntrue } var m, n = 0, len(nums) for i := 0; i < len(nums) - 1; i++{ if m < i{ break } m = max(m, i + nums[i]) if m >= n - 1{ returntrue } } returnfalse }
funcmax(x,y int)int{ if x > y{ return x } return y }
funcjump(nums []int)int { var maxB, broad, ans int// 可到达的最远区域 for i := 0; i < len(nums) - 1; i++{ maxB = max(maxB, i + nums[i]) if i == broad{ broad = maxB ans++ } } return ans }
funcmax(x, y int)int{ if x > y{ return x } return y }
func(this *RandomizedSet) GetRandom() int { return this.nums[rand.Intn(len(this.nums))] }
/** * 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(); */
funccanCompleteCircuit(gas []int, cost []int)int { for i, n := 0, len(gas); i < n; { var sumOfGas, sumOfCost, cnt int for cnt < n{ var j = (i + cnt) % n sumOfGas += gas[j] sumOfCost += cost[j]
if sumOfCost > sumOfGas{ break } cnt++ }
if cnt == n{ // 循环了 return i } // 下一个不能到达的加油站 i += cnt + 1 } return-1 }