Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does Java find the subarray with K

Shulou Source: shulou.com Published: 2022-06-01 10:55:04 10月01日 Update

This article mainly explains "how to find a subarray of Java and K". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to find a subarray of K by Java".

Preorder sum

The definition sumi represents the sum added to the position I from the beginning, which we have on the array [1, 2, 3, 4].

Sum [0] = nums [0]

Sum [1] = nums [0] + nums [1] = sum [0] + nums [1]

Sum [2] = nums [0] + nums [1] + nums [2] = sum [0] + nums [1] + nums [2] = sum [1] + nums [2]

Sum [3] = nums [0] + nums [1] + nums [2] + nums [3] = sum [0] + nums [1] + nums [2] + nums [3] =.

We found that we have done a lot of repeated calculations, and these are the places where we can optimize and deform the third formula above.

Sum [1]-sum [0] = nums [1]

Sum [2]-sum [0] = nums [1] + nums [2]

Sum [2]-sum [1] = nums [2]

Sum [I]-sum [j] is the sum of consecutive arrays between sum [I]-sum [j] = k, then we can count, here we can also do a transformation sum [j] = sum [I]-k, we use a hash table to record sum [j], and we count when it occurs again.

Func subarraySum (nums [] int, k int) int {res,sum,m: = 0Pol 0, map [int] int {0:1} for iRu return res} i0 {res + = m [sum-k]} m [sum] +} return res} so far, I believe you have a deeper understanding of "how to find a subarray of Java and a subarray of K", you might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Array content that is learning practical deeper between location interest again place practicality formula simple operation method time more friends website Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Apple macOS Linux Shulou Technology