topic:
1590.Make the array and energyPDivide.md
Thought:
‘≡’Together
For example nums=[11,2,5,7,8,9],p=10,So [5,7] Remove,The remaining numbers add 30,Be able to p Divide。
All elements and $42mod10 = 2$
设All elements andx,RemoveElementsand为y,Makex-y Be able topDivide,satisfy
y≡x(mod p)->x % p = y % p
By prefix and,The problem converts:Find two numbers on the prefix and array s[left]
and s[right]
,satisfy right−left Minimum
$$
s[right] - s[left] ≡ x (mod p)
->s[right] - x ≡ s[left] (mod p)
$$
((s[right]-x)modp+p) mod p = s[left] mod p
Traversal sss At the same time,Hash table last\textit{last}last Record s[i]mod p The last time the bidding appeared,if lastlast Contain
(s[i] mod p−x mod p+p) mod p,Let’s set its corresponding setting j,So [j,i) Is a符合topic要求的子数组。
Enumerate i,Calculate the minimum value of the child array length that meets the requirements,Is the answer。if没有符合要求的子数组,Then return −1。
Code implementation,You can initialize the answer to nums length n。if最后答案等于 n,It means that there are no sub -array that does not meet the requirements,因为topic不允许将整个数组都移除。
lastIs amap,The key is an integer,Value is an integer。j, ok := last[(v-x+p)%p]This line code is inlastThe search key is(v-x+p)%pElements,And give its value to variablesj。if这个键不存在,SookThe value will befalse,otherwiseokThe value will betrue。
The return value of this grammar is two values,The first value is the value corresponding to the key,第二个值Is a布尔值,Indicates whether the key exists。
ifokThe value istrue,SoCode中的ifThe statement will be executed,It willansThe value update isi-jandansMinimum value。ifokThe value isfalse,SoifThe statement will be skipped,The program will continue to execute。
Code:
1 | class Solution: |
1 | package main |