问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4003 访问。

我们把符合下列属性的数组 A 称作山脉:

  • A.length >= 3
  • 存在 0 < i < A.length - 1 使得A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]

给定一个确定为山脉的数组,返回任何满足 A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] 的 i 的值。

输入:[0,1,0]

输出:1

输入:[0,2,1,0]

输出:1

提示:

  • 3 <= A.length <= 10000
  • 0 <= A[i] <= 10^6
  • A 是如上定义的山脉

Let's call an array A a mountain if the following properties hold:

  • A.length >= 3
  • There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]

Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].

Input: [0,1,0]

Output: 1

Input: [0,2,1,0]

Output: 1

Note:

  • 3 <= A.length <= 10000
  • 0 <= A[i] <= 10^6
  • A is a mountain, as defined above.

示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4003 访问。

public class Program {

    public static void Main(string[] args) {
var A = new int[] { 24, 69, 100, 99, 79, 78, 67, 36, 26, 19 }; var res = PeakIndexInMountainArray(A);
Console.WriteLine(res); Console.ReadKey();
} private static int PeakIndexInMountainArray(int[] A) {
//二分法
var low = 1;
var high = A.Length - 2;
var mid = 0;
while(low <= high) {
mid = low + (high - low) / 2;
var top = Position(A, mid);
if(top == 1) {
high = mid - 1;
} else if(top == -1) {
low = mid + 1;
} else {
return mid;
}
}
return -1;
} private static int Position(int[] A, int index) {
//-1,index在峰顶左边
//1,index在峰顶右边
//0,index是峰顶
if(A[index] > A[index - 1] && A[index + 1] > A[index]) return -1;
if(A[index + 1] < A[index] && A[index] < A[index - 1]) return 1;
return 0;
} }

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4003 访问。

2

分析:

显而易见,以上算法的时间复杂度为:  。

最新文章

  1. PHP中的SESSION机制
  2. 【bzoj2120】 数颜色
  3. 原生 js 左右切换轮播图
  4. spring mvc+mybatis+多数据源切换
  5. simple-LDAP-auth
  6. 通过CoreImage生成二维码
  7. 基础知识 - Rabin-Karp 算法
  8. 关于O(n)算法
  9. queue 之团队队列(摘)
  10. 前端开发之基础知识-HTML(二)
  11. AI 基础
  12. 1.1.15 word调整文字与下划线之间的间距
  13. 加密与解密md5 3des
  14. host大法之GitHub上不去
  15. MySQL 5.6新特性 -- Index Condition Pushdown
  16. yaml文件 *.yml 写法简介
  17. JavaScript 删除 ASP.NET 设置的多值 Cookie 的方法
  18. __getattr__,settr
  19. 英雄无敌3开源引擎vcmi的编译安装
  20. Matlab 调用Oracle数据库

热门文章

  1. Ethical Hacking - GAINING ACCESS(3)
  2. Ethical Hacking - NETWORK PENETRATION TESTING(14)
  3. MapReduce之MapTask工作机制
  4. 题解 洛谷 P3340 【[ZJOI2014]星系调查】
  5. 细说JavaScript 导出 上万条Excel数据
  6. Go 中读取命令参数的几种方法总结
  7. Laragon修改配置快速创建其他框架的项目
  8. java 控制语句、数组、方法
  9. Python日历模块
  10. PHP 怎么安装