分饼干
func findContentChildren(g []int, s []int) int {// 第一思路,双指针暴力解法var count intvar used2 = make([]bool, len(s))g = quicksort(g)s = quicksort(s)for _, child := range g {for idx, cookie := range s {if !used2[idx] && cookie >= child{used2[idx] = truecount++break // 该child分到饼干就退出循环,让下一个child参与}}}return count}func quicksort(li []int) []int{if len(li) == 0 {return nil}r := rand.New(rand.NewSource(time.Now().Unix()))povid := li[r.Intn(len(li))] // 随机值作为基准var left, right, equal []intfor _, l := range li {if l > povid {right = append(right, l)}else if l < povid {left = append(left, l)}else {equal = append(equal, l)}}left = quicksort(left)right = quicksort(right)return append(left, append(equal, right...)...)}// 必须要排序,不然可能出现最大的饼干分给需求最小的child,导致后面较大的需求无法满足
时间 快排nlogn * 2 + n^2 空间 n
func findContentChildren(g []int, s []int) int {// 第一思路,另一种写法var count intvar idxs intg = quicksort(g)s = quicksort(s)for _, child := range g {for idxs < len(s) {if s[idxs] >= child {count++idxs++break}idxs++}}return count
}
376 摆动序列
func wiggleMaxLength(nums []int) int {// 思路 遇到相邻元素积是0或者负数,计数加一if len(nums) == 1 {return 1}var diffpre, diff, count intfor i := 1; i < len(nums); i++ {diff = nums[i] - nums[i - 1]if diffpre <= 0 && diff > 0 ||diffpre >= 0 && diff < 0 {count++}if diff != 0 { // 出现单调情况再赋值,避免出现情况4也被统计diffpre = diff}}return count + 1
}
53 最大子序列和
func maxSubArray(nums []int) int {// 分别存储连续和以及最大和,连续和不断贪心往后累加,如果大于最大和就更新最大和// 连续和更新逻辑,如果目前大于0,往后累加,如果小于0,舍弃,直接等于当前元素var sum, maxsum intmaxsum = math.MinIntfor _, v := range nums {if sum >= 0 {sum += v}else {sum = v}if sum > maxsum {maxsum = sum}}return maxsum
}