[Programming questions] virus detection Golang mathematical solution Racer 2020

[Programming questions] virus detection

Recently focused brush questions, write it all a bit time-consuming, since you only do records more difficult.
This question is a pleasant to the eye My first thought is a two-pointer, but consider carefully find the right way of thinking about the pointer turns will not work, if we use double pointer, you need the right pointer back to the beginning again finished scanning operation, and this violence law no difference.
I thought of another idea, create an array pos [] record the location of each 1.
We combine an example to analyze the general case, for the following pos []:

2 4 9 10 14 18

Consider a fifth, position 14, if k = 3, the second position is 1 4.
All these three possibilities then contain 1, 10, 11 may be expressed as:
right sliding range (14, 18], the left sliding range ((4,9], there is the possibility of (18-14) * ( 9-4) = 20 kinds.
then the possibility of changing the last bit position 1 of the determined total.

Lower attachment Code:

package main

import "fmt"

func main()  {
	var k,ans int
	var str string
	fmt.Scan(&k,&str)
	pos:= []int{-1}
	for i,v:=range(str){
		if v==49{	//"1"的ASCII码为49
			pos=append(pos, i)
		}
	}
	if k>=len(pos){
		fmt.Println(0)
		return
	}
	pos=append(pos, len(str))
	if k==0{
		for i:=k;i<len(pos)-1;i++{
			ans+=(pos[i+1]-pos[i]-1)*(pos[i+1]-pos[i])/2
		}
	}else {
		for i := k; i < len(pos)-1; i++ {
			ans += (pos[i+1] - pos[i]) * (pos[i-k+1] - pos[i-k])
		}
	}
	fmt.Println(ans)
}
Published 38 original articles · won praise 0 · Views 1011

Guess you like

Origin blog.csdn.net/Cyan1956/article/details/105328680