From acaca3d6715303f951d3b97b325e2c60422a5da0 Mon Sep 17 00:00:00 2001 From: Lanre Adedara Date: Fri, 31 May 2024 07:34:36 +0100 Subject: [PATCH] Swift implementation for LCOF2 009 --- .../README.md" | 25 +++++++++++++++++++ .../Solution.swift" | 20 +++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 "lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.swift" diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/README.md" index ec70e74276af0..207030eeb2241 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/README.md" @@ -149,6 +149,31 @@ function numSubarrayProductLessThanK(nums: number[], k: number): number { } ``` +#### Swift + +```swift +class Solution { + func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int { + if k <= 1 { return 0 } + + var product: Int = 1 + var ans: Int = 0 + var left: Int = 0 + + for right in 0..= k { + product /= nums[left] + left += 1 + } + ans += right - left + 1 + } + + return ans + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.swift" new file mode 100644 index 0000000000000..efd1c9f9b9751 --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 009. \344\271\230\347\247\257\345\260\217\344\272\216 K \347\232\204\345\255\220\346\225\260\347\273\204/Solution.swift" @@ -0,0 +1,20 @@ +class Solution { + func numSubarrayProductLessThanK(_ nums: [Int], _ k: Int) -> Int { + if k <= 1 { return 0 } + + var product: Int = 1 + var ans: Int = 0 + var left: Int = 0 + + for right in 0..= k { + product /= nums[left] + left += 1 + } + ans += right - left + 1 + } + + return ans + } +} \ No newline at end of file