※ 引述《yam276 (史萊哲林的優等生)》之銘言:
: 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
: }
: }
用 if else 暴力硬肛 連變數都不用
----------------------------------------------
class Solution {
public boolean isMonotonic(int[] nums) {
int n = nums.length;
if (nums[0] < nums[n - 1]) {
for (int i = 1; i < n; i++) {
if (nums[i] < nums[i - 1]) {
return false;
}
}
} else {
for (int i = 1; i < n; i++) {
if (nums[i] > nums[i - 1]) {
return false;
}
}
}
return true;
}
}
----------------------------------------------
--
https://i.imgur.com/PIoxddO.jpg
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1696087573.A.593.html