Re: [闲聊] 每日LeetCode

楼主: ZooseWu (N5)   2023-11-23 12:31:03
1630. Arithmetic Subarrays
给你一个整数阵列还有左右边界的阵列
回传左右边界夹起来的子阵列能不能变成一个等差数列
Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]
Output: [true,false,true]
[0,2]夹起来的数列是[4,6,5] 可以变成等差数列
[0,3]夹起来的数列是[4,6,5,9] 不可以变成等差数列
[2,5]夹起来的数列是[5,9,3,7] 可以变成等差数列
Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10],
l = [0,1,6,4,8,7],
r = [4,4,9,7,9,10]
Output: [false,true,false,false,true,true]
把子阵列找出来之后排序看是不是等差数列
TS Code:
function checkArithmeticSubarrays (nums: number[], l: number[], r: number[]):
boolean[] {
const result: boolean[] = []
for (let i = 0; i < l.length; i++) {
const subArray = nums.slice(l[i], r[i] + 1)
subArray.sort((a, b) => a - b)
let isArithmetic = true
let diff = subArray[1] - subArray[0]
for (let i = 2; i < subArray.length; i++) {
isArithmetic = (subArray[i] - subArray[i - 1]) === diff
if (!isArithmetic) break;
}
result.push(isArithmetic)
}
return result
}
作者: oin1104 (是oin的说)   2023-11-23 12:46:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com