Re: [閒聊] 每日leetcode

作者: JIWP (JIWP)   2024-12-09 21:35:47
3152. Special Array II
去用prefix_sum紀錄有幾組奇偶對數
如果nums[i]跟nums[i-1]奇偶性不同
那prefix_sum[i]=prefix_sum[i-1]+1
ex [1,2,3,4,5,6]
prefix_sum=[0,1,2,3,4,5]
接著就去看每組queries內有沒有足夠的奇偶對數
假設from=1、to=4
那這樣要有3組奇偶對才會是true
golang code :
func isArraySpecial(nums []int, queries [][]int) []bool {
n:=len(queries)
res:=make([]bool,n)
prefix:=make([]int,len(nums))
for i:=1;i<len(nums);i++{
if (nums[i]+nums[i-1]) & 1==1{
prefix[i]=1
}
prefix[i]+=prefix[i-1]
}
for key,val:=range queries{
tmp:=val[1]-val[0]
if prefix[val[1]]-prefix[val[0]]==tmp{
res[key]=true
}
}
return res
}
作者: sustainer123 (caster)   2024-12-09 21:37:00
大師
作者: Furina (芙寧娜)   2024-12-09 21:45:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com