日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

75. Find Peak Element 【medium】

發布時間:2023/11/27 生活经验 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 75. Find Peak Element 【medium】 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

There is an integer array which has the following features:

  • The numbers in adjacent positions are different.
  • A[0] < A[1] && A[A.length - 2] > A[A.length - 1].

We define a position P is a peek if:

A[P] > A[P-1] && A[P] > A[P+1]

Find a peak element in this array. Return the index of the peak.

?Notice
  • It's guaranteed the array has at least one peak.
  • The array may contain multiple peeks, find any of them.
  • The array has at least 3 numbers in it.
Example

Given?[1, 2, 1, 3, 4, 5, 7, 6]

Return index?1?(which is number 2) or?6?(which is number 7)

Challenge?

Time complexity O(logN)

?

解法一:

 1 class Solution {
 2 public:
 3     /*
 4      * @param A: An integers array.
 5      * @return: return any of peek positions.
 6      */
 7     int findPeak(vector<int> &A) {
 8         if (A.empty()) {
 9             return -1;
10         }
11         
12         int start = 0;
13         int end = A.size() - 1;
14         
15         while (start + 1 < end) {
16             int mid = start + (end - start) / 2;
17             
18             if (A[mid] > A[mid - 1]) {
19                 if (A[mid] > A[mid + 1]) {
20                     return mid;
21                 }
22                 else {
23                     start = mid;
24                 }
25             }
26             else {
27                 if (A[mid] > A[mid + 1]) {
28                     end = mid;
29                 }
30                 else {
31                     start = mid;    
32                 }
33             }
34         }
35         
36         return -1;
37     }
38 };

分類討論。

?

解法二:

 1 class Solution {
 2     /**
 3      * @param A: An integers array.
 4      * @return: return any of peek positions.
 5      */
 6     public int findPeak(int[] A) {
 7         // write your code here
 8         int start = 1, end = A.length-2; // 1.答案在之間,2.不會出界 
 9         while(start + 1 <  end) {
10             int mid = (start + end) / 2;
11             if(A[mid] < A[mid - 1]) {
12                 end = mid;
13             } else if(A[mid] < A[mid + 1]) {
14                 start = mid;
15             } else {
16                 end = mid;
17             }
18         }
19         if(A[start] < A[end]) {
20             return end;
21         } else { 
22             return start;
23         }
24     }
25 }

參考http://www.jiuzhang.com/solution/find-peak-element/的解法,此法更簡單。

?

轉載于:https://www.cnblogs.com/abc-begin/p/7551585.html

總結

以上是生活随笔為你收集整理的75. Find Peak Element 【medium】的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。