我们得到一个数字序列,作为向量foo
.任务是找出is foo
是monotonically increasing——每一项都小于或等于下一项——或者monotonically decreasing——每一项都大于或等于下一项.
当然,这可以通过一个循环找到,但还有其他创意吗?
我们得到一个数字序列,作为向量foo
.任务是找出is foo
是monotonically increasing——每一项都小于或等于下一项——或者monotonically decreasing——每一项都大于或等于下一项.
当然,这可以通过一个循环找到,但还有其他创意吗?
另一个:判断一下
all(x == cummax(x))
或
all(x == cummin(x))
f或 monotonously increasing 或 decreasing respectively. It seems that cummax
is a lot faster than diff
and also uses less mem或y:
> x <- seq_len(1e7)
> system.time(all(x == cummax(x)))
user system elapsed
0.11 0.00 0.11
> system.time(all(diff(x) >= 0))
user system elapsed
0.47 0.13 0.59
> x <- seq_len(1e8)
> system.time(all(x == cummax(x)))
user system elapsed
1.06 0.09 1.16
> system.time(all(diff(x) >= 0))
Err或: cannot allocate vect或 of size 381.5 Mb
In addition: Warning messages:
1: Reached total allocation of 1535Mb: see help(mem或y.size)
2: Reached total allocation of 1535Mb: see help(mem或y.size)
3: Reached total allocation of 1535Mb: see help(mem或y.size)
4: Reached total allocation of 1535Mb: see help(mem或y.size)
Timing stopped at: 1.96 0.38 2.33
关于为什么cummax
比diff
快,我打赌是因为它只需要比较比计算差更快的数字.
Edit:应你(阿里)的要求,额外的测试包括你的答案(注意,我现在在另一台机器上运行,因此以下结果不应与上述结果进行比较)
> x <- seq_len(1e7)
> system.time(x == cummax(x))
user system elapsed
0.316 0.096 0.416
> system.time(all(diff(x) >= 0))
user system elapsed
4.364 0.240 4.632
> system.time(x[-1] - x[-length(x)] >= 0)
user system elapsed
3.828 0.380 4.227
> system.time(all(x[-1] >= x[-length(x)]))
user system elapsed
2.572 0.288 2.865