Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 13a7c81

Browse files
committed
another code for subarray product less than k sliding window solution
1 parent 2aa6a6c commit 13a7c81

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

‎src/0713_subarray_product_less_than_k/spltk.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ package spltk
1616
// time complexity: O(n), where n = len(nums)
1717
// space complexity: O(1)
1818
func numSubArrayProductLessThanK(nums []int, k int) int {
19-
if k <= 0 {
19+
if k <= 1 {
2020
return 0
2121
}
2222

@@ -42,3 +42,25 @@ func numSubArrayProductLessThanK(nums []int, k int) int {
4242
}
4343
return res
4444
}
45+
46+
// 2019年06月16日
47+
func numSubArrayProductLessThanK2(nums []int, k int) int {
48+
if k <= 1 {
49+
return 0
50+
}
51+
var (
52+
prod = 1
53+
res = 0
54+
left = 0
55+
)
56+
57+
for right, val := range nums {
58+
prod *= val
59+
for prod >= k {
60+
prod /= nums[left]
61+
left++
62+
}
63+
res += right - left + 1
64+
}
65+
return res
66+
}

‎src/0713_subarray_product_less_than_k/spltk_test.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,16 @@ func TestNumSubArrayProductLessThanK(t *testing.T) {
1111

1212
ks := []int{100, 0, 100}
1313
expected := []int{8, 0, 4}
14-
for index, data := range testCases {
15-
if res := numSubArrayProductLessThanK(data, ks[index]); res != expected[index] {
16-
t.Errorf("expected %d, got %d", expected[index], res)
14+
15+
functions := []func([]int, int)int{
16+
numSubArrayProductLessThanK,
17+
numSubArrayProductLessThanK2,
18+
}
19+
for _, func_ := range functions {
20+
for index, data := range testCases {
21+
if res := func_(data, ks[index]); res != expected[index] {
22+
t.Errorf("expected %d, got %d", expected[index], res)
23+
}
1724
}
1825
}
1926
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /