File tree
Expand file treeCollapse file tree2 files changed
+33
-4
lines changed src/0713_subarray_product_less_than_k
Expand file treeCollapse file tree2 files changed
+33
-4
lines changed Original file line number | Diff line number | Diff line change |
---|
@@ -16,7 +16,7 @@ package spltk
|
16 | 16 | // time complexity: O(n), where n = len(nums)
|
17 | 17 | // space complexity: O(1)
|
18 | 18 | func numSubArrayProductLessThanK(nums []int, k int) int {
|
19 |
| -if k <= 0 { |
| 19 | +if k <= 1 { |
20 | 20 | return 0
|
21 | 21 | }
|
22 | 22 |
|
@@ -42,3 +42,25 @@ func numSubArrayProductLessThanK(nums []int, k int) int {
|
42 | 42 | }
|
43 | 43 | return res
|
44 | 44 | }
|
| 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 | +} |
Original file line number | Diff line number | Diff line change |
---|
@@ -11,9 +11,16 @@ func TestNumSubArrayProductLessThanK(t *testing.T) {
|
11 | 11 |
|
12 | 12 | ks := []int{100, 0, 100}
|
13 | 13 | 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 | +} |
17 | 24 | }
|
18 | 25 | }
|
19 | 26 | }
|
You can’t perform that action at this time.
0 commit comments