Two questions a day T30

Two questions a day T30

algorithm

LeetCode T1248. Statistics "beautiful sub-array" [1]

description

To give you an array of integers numsand an integer k.

If you happen to have a continuous sub-array kodd numbers, we believe that this is a sub-array "Yumiko array」 .

Please return the number of "beautiful sub-arrays" in this array .

Example 1:

Input: nums = [1,1,2,1,1], k = 3
Output: 2
Explanation: The sub-arrays containing 3 odd numbers are [1,1,2,1] and [1,2,1,1].

Example 2:

Input: nums = [2,4,6], k = 1
Output: 0
Explanation: The sequence does not contain any odd numbers, so there is no graceful sub-array.

Example 3:

Input: nums = [2,2,2,1,2,2,1,2,2,2], k = 2
Output: 16

prompt:

1 <= nums.length <= 500001 <= nums[i] <= 10^51 <= k <= nums.length

analysis

Clever solution, go directly to the code in detail.

Code

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
const numberOfSubarrays = (nums, k) => {
  let n = nums.length, counts = new Array(n + 1).fill(0).fill(1, 0, 1), oddCount = 0, result = 0
  for (let i = 0; i <n; i++) {
    oddCount += nums[i] & 1
    result += oddCount >= k? counts[oddCount-k]: 0
    counts[oddCount] += 1
  }
  return result
}

front end

Typical example of using this

•Implicit binding:

var b = {
    a: function() {
        console.log(this);
    }
}
ba();
//this is b

•Explicit binding:

bacall(this);//this is window

•New binding

function B() { 
    this.a = function() {console.log(this.b)}, 
    this.b = 1
}
let b = new B();
ba();
//this is b object;

•Window binding

var a = 1;
this.a;

References

[1]1248. Statistics of ``beautiful subarrays'': https://leetcode-cn.com/problems/count-number-of-nice-subarrays/

Reference: https://cloud.tencent.com/developer/article/1664381 Two questions a day T30-Cloud + Community-Tencent Cloud