Re: [閒聊] 每日LeetCode

作者: yam276 ('_')   2023-09-30 00:16:45
896. Monotonic Array
判斷輸入的陣列是否為遞減或遞增
思路:
看到別人以下的簡潔解法我破防了
建立is遞增跟is遞減的bool變數為true
從1開始跑for 如果是遞增數列 is遞減就為false
如果是遞減數列 is遞增就為false
return is遞增 || is遞減
Code:
impl Solution {
pub fn is_monotonic(nums: Vec<i32>) -> bool {
let mut is_increasing = true;
let mut is_decreasing = true;
for index in 1..nums.len() {
if nums[index] > nums[index - 1] {
is_decreasing = false;
}
if nums[index] < nums[index - 1] {
is_increasing = false;
}
}
is_increasing || is_decreasing
}
}
作者: smart0eddie (smart0eddie)   2023-09-30 00:32:00
不然你原本打算怎麼做
作者: yam276 ('_')   2023-09-30 00:33:00
我就爛我本來只有用一個變數算遞增遞減趨勢用兩個就省很多時間

Links booklink

Contact Us: admin [ a t ] ucptt.com