牛客:[编程题]万万没想到之抓捕孔连顺

链接

木有,全部贴上来不大好吧

难度:

middle

解答:

拿到题不慌,首先分析这是干啥的。其实就是个组合问题,现在问题的关键就是找准组合的起始地址。虽然是嵌套循环,但是每个元素只是被i或者j遍历2次,所以复杂度还是n

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func convInts(ss []string) []int {
	result := make([]int, len(ss))
	for i, v := range ss {
		res, err := strconv.ParseInt(v, 10, 64)
		if err != nil {
			panic(err)
		}

		result[i] = int(res)
	}

	return result
}

func ambush(dist int, pos []int) {
	total := 0
	prej := -1
	for i := 0; i < len(pos); i++ {
		maxPos := pos[i] + dist
		for j := prej + 1; j < len(pos); j++ {
			if pos[j] <= maxPos {
				prej = j
			} else {
				break
			}
		}

		cnt := prej - i
		if cnt > 0 {
			total += cnt * (cnt - 1) / 2
		}
	}

	fmt.Println(total % 99997867)
}

func main() {
	rd := bufio.NewReader(os.Stdin)

	s, _ := rd.ReadString('\n')
	s = strings.TrimSpace(s)
	ss := strings.Split(s, " ")
	is := convInts(ss)
	cnt, dist := is[0], is[1]

	s, _ = rd.ReadString('\n')
	s = strings.TrimSpace(s)
	ss = strings.Split(s, " ")
	is = convInts(ss)
	pos := is

	//fmt.Println(cnt, dist, pos)
	if cnt != len(pos) {
		panic("cnt != len(pos)")
	}

	ambush(dist, pos)
}

复杂度分析

time

O(n)

space

O(1)

执行结果

你可能感兴趣的:(leetcode)