funcfindWinners(matches [][]int) [][]int { m := make(map[int]int) for _, match := range matches { if m[match[0]] == 0 { m[match[0]] = 0 } m[match[1]]++ } res := make([][]int, 2) for user, count := range m { if count < 2 { res[count] = append(res[count], user) } } sort.Ints(res[0]) sort.Ints(res[1]) return res }
funclongestEqualSubarray(nums []int, k int)int { pos := make(map[int][]int) for i, num := range nums { pos[num] = append(pos[num], i) } res := 0 for _, p := range pos { left := 0 for right := range p { for p[right]-p[left]-right+left > k { left++ } res = max(res, right-left+1) } } return res }
p[right]−p[left]−(right−left) 可以变换一下改为 p[right]−right−(p[left]−left),我们将 p 中存储下标改为 p[i]−i,这样上述式子就可以改为:
p[right]−p[left]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funclongestEqualSubarray(nums []int, k int)int { pos := make(map[int][]int) for i, num := range nums { pos[num] = append(pos[num], i-len(pos[num])) } res := 0 for _, p := range pos { left := 0 for right := range p { for p[right]-p[left] > k { left++ } res = max(res, right-left+1) } } return res }
funcfindIndices(nums []int, indexDifference int, valueDifference int) []int { for i := 0; i < len(nums); i++ { for j := i; j < len(nums); j++ { if j-i >= indexDifference && abs(nums[i], nums[j])>= valueDifference{ return []int{i, j} } } } return []int{-1,-1} } funcabs(a, b int)int { if a > b { return a - b } return b - a }
通过双指针 i 和 j 维护一个间隔为 indexDifference 的滑动窗口,初始时 i 指向 0,j 指向 indexDifference。
funckthLargestValue(matrix [][]int, k int)int { m, n := len(matrix), len(matrix[0]) arr := make([]int, 0, m*n) colSum := make([]int, n) for _, row := range matrix { sum := 0 for j, x := range row { colSum[j] ^= x sum ^= colSum[j] arr = append(arr, sum) } } sort.Ints(arr) return arr[len(arr)-k] }