Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2025-04-27 18:44:26
※ 引述《yam276 (史莱哲林的优等生)》之铭言:
: 3392. Count Subarrays of Length Three With a Condition
: https://leetcode.com/problems/count-subarrays-of-length-three-with-a-condition/
: 简单来说 任意三个数的子阵列切片
: 中间的数 要是两边相加除二
: 思考:
: Sliding Windows
: 而且 Rust 居然有内建 .widnows() 函数
: 没内建的语言用
: for i in 0..nums.len()-2 {
: let a = nums[i];
: let b = nums[i+1];
: let c = nums[i+2];
: // ...
: }
: Code:
: impl Solution {
: pub fn count_subarrays(nums: Vec<i32>) -> i32 {
: nums.windows(3)
: .filter(|w| w[1] % 2 == 0 && w[1] / 2 == w[0] + w[2])
: .count() as i32
: }
: }
思路:
照题目叙述做题 一路滑到底就是答案
Python Code:
class Solution:
def countSubarrays(self, nums: List[int]) -> int:
result = 0
for i in range(len(nums)-2):
if nums[i] + nums[i+2] == nums[i+1] / 2:
result += 1
return result
作者: yam276 ('_')   2025-04-27 18:50:00
不用考虑中间数是偶数吗
楼主: sustainer123 (caster)   2025-04-27 18:53:00
奇数除出来就浮点数 一定不等于所以没差ㄅ
作者: yam276 ('_')   2025-04-27 18:54:00
哀 只有PY可以这样玩了恨动态语言
楼主: sustainer123 (caster)   2025-04-27 18:55:00
py就是这点方便不过工作没写好就会喷怪东西 哀

Links booklink

Contact Us: admin [ a t ] ucptt.com