-
Notifications
You must be signed in to change notification settings - Fork 2
/
monotonic-array.rs
60 lines (46 loc) · 1.12 KB
/
monotonic-array.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#![allow(dead_code, unused, unused_variables)]
fn main() {}
struct Solution;
impl Solution {
pub fn is_monotonic1(a: Vec<i32>) -> bool {
if a.len() <= 1 {
return true;
}
let mut f = None;
for i in 1..a.len() {
if a[i] == a[i - 1] {
continue;
}
if f.is_none() {
f = Some(a[i] > a[i - 1]);
}
if let Some(s) = f {
if s && a[i] < a[i - 1] {
return false;
}
if !s && a[i] > a[i - 1] {
return false;
}
}
}
true
}
pub fn is_monotonic(a: Vec<i32>) -> bool {
if a.len() <= 1 {
return true;
}
let mut s = 0;
for i in 1..a.len() {
if a[i] == a[i - 1] {
continue;
}
if s == 0 && a[i] - a[1] != 0 {
s = a[i] - a[i - 1];
}
if s * a[i] - a[i - 1] < 0 {
return false;
}
}
true
}
}