在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array of integers nums and an integer k. A subarray is called nice if there are k odd numbers on it. Return the number of nice sub-arrays. Example 1: Input: nums = [1,1,2,1,1], k = 3 Input: nums = [2,4,6], k = 1 Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2 Constraints: 1 <= nums.length <= 50000 给你一个整数数组 nums 和一个整数 k。 如果某个 连续 子数组中恰好有 k 个奇数数字,我们就认为这个子数组是「优美子数组」。 请返回这个数组中「优美子数组」的数目。 示例 1: 输入:nums = [1,1,2,1,1], k = 3 输入:nums = [2,4,6], k = 1 输入:nums = [2,2,2,1,2,2,1,2,2,2], k = 2 提示: 1 <= nums.length <= 50000 1056ms 1 class Solution { 2 func numberOfSubarrays(_ nums: [Int], _ k: Int) -> Int { 3 var oddIndex = [Int]() 4 var res = 0 5 var p = 0 6 for i in 0 ..< nums.count where nums[i] % 2 != 0 { 7 if oddIndex.count >= k { 8 res += (oddIndex[p] - (p > 0 ? oddIndex[p - 1] : -1)) * (i - oddIndex.last!) 9 p += 1 10 } 11 oddIndex.append(i) 12 } 13 14 if oddIndex.count >= k { 15 res += (oddIndex[p] - (p > 0 ? oddIndex[p - 1] : -1)) * (nums.count - oddIndex.last!) 16 } 17 18 return res 19 } 20 } 1068ms 1 class Solution { 2 func numberOfSubarrays(_ nums: [Int], _ k: Int) -> Int { 3 return atMostK(nums, k) - atMostK(nums, k - 1) 4 } 5 6 private func atMostK(_ nums: [Int], _ count: Int) -> Int { 7 var count = count 8 var res = 0 9 var i = 0 10 for j in 0..<nums.count { 11 if nums[j] % 2 == 1 { 12 count -= 1 13 } 14 15 while count < 0 { 16 if nums[i] % 2 == 1 { 17 count += 1 18 } 19 i += 1 20 } 21 res += j - i + 1 22 } 23 return res 24 } 25 } 1076ms 1 class Solution { 2 func numberOfSubarrays(_ nums: [Int], _ k: Int) -> Int { 3 if nums.count == 0 { 4 return 0 5 } 6 var oddPosition : [Int] = [] 7 for i in 0...nums.count - 1 { 8 if nums[i] % 2 == 1 { 9 oddPosition.append(i) 10 } 11 } 12 if oddPosition.count < k { 13 return 0 14 } 15 oddPosition.insert(-1,at:0) 16 oddPosition.append(nums.count) 17 18 var result = 0 19 for i in 1...oddPosition.count - k - 1 { 20 result += (oddPosition[i] - oddPosition[i-1])*(oddPosition[i+k] - oddPosition[i+k-1]) 21 } 22 return result 23 } 24 }
|
请发表评论