You are given an integer array nums and an integer digit x.
A subarray nums[l..r] is considered valid if the sum of its elements satisfies both of the following conditions:
The first digit of the sum is equal to x.
The last digit of the sum is equal to x.
Return the number of valid subarrays.
Example 1:
Input: nums = [1,100,1], x = 1
Output: 4
Explanation:
The valid subarrays are:
nums[0..0]: sum = 1
nums[0..1]: sum = 1 + 100 = 101
nums[1..2]: sum = 100 + 1 = 101
nums[2..2]: sum = 1
Thus, the answer is 4.
Example 2:
Input: nums = [1], x = 2
Output: 0
Explanation:
The only subarray is nums[0..0] with a sum of 1, which does not satisfy the conditions.
Thus, the answer is 0.
Constraints:
1 <= nums.length <= 1500
1 <= nums[i] <= 10^9
1 <= x <= 9
這題是週賽第二題,
題目給我們一個一維陣列 nums 還有一個正整數 x,
x 滿足 1 <= x <= 9。
題目希望我們找符合條件的子陣列數量,
條件是子陣列總和的最高位與最低位都要等於 x。
看到子陣列總和就是 prefix sum,
這題我先用 prefix sum 然後 to_string 去轉,結果太慢(#,
早上卡在這邊一度尷尬。
假設子陣列總共有 M 個位元,雖然手動判斷也是 O(M) 跟 to_string 理論上一樣,
但總能比 to_string 少作一些步驟,只取頭尾兩位,所以把 to_string 換成手動判斷就好。
因為每個子陣列總和最多 10^12,
所以每個最內圈計算最多 O(12) ~= O(1)。
C++程式碼: