From 25f3c053d2d3032b15fd96f461fd3a204b46910b Mon Sep 17 00:00:00 2001 From: xliu45 Date: Fri, 4 Mar 2016 21:47:39 -0600 Subject: [PATCH 1/2] C++/162_Find_Peak_Element.cpp --- C/162_Find_Peak_Element.cpp | 53 +++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 C/162_Find_Peak_Element.cpp diff --git a/C/162_Find_Peak_Element.cpp b/C/162_Find_Peak_Element.cpp new file mode 100644 index 00000000..1d7ebe56 --- /dev/null +++ b/C/162_Find_Peak_Element.cpp @@ -0,0 +1,53 @@ +//162. Find Peak Element +/* +A peak element is an element that is greater than its neighbors. +Given an input array where num[i] ≠ num[i+1], find a peak element and return its index. +The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. +You may imagine that num[-1] = num[n] = -∞. + +Example: +in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2. + +Tag: Array, Binary Search + +Author: Xinyu Liu +*/ + +#include +#include +using namespace std; + +class Solution { + +public: + int findPeakElement(vector& nums) { + int sz = nums.size(); + if (sz == 1) + return 0; + if (nums.at(0) > nums.at(1)) + return 0; + if (nums.at(sz - 1) > nums.at(sz - 2)) + return sz - 1; + + for(int i = 1; i < nums.size(); i++) + { + if (nums.at(i - 1) < nums.at(i) & nums.at(i) > nums.at(i + 1)) + return i; + } + return -1; + } +}; + +void main(int argc, char ** argv){ + + // Initialize vector + int myints[] = {1, 2, 3, 4, 3}; + int index; + std::vector test (myints, myints + sizeof(myints) / sizeof(int) ); + + Solution sol; + index = sol.findPeakElement (test); + + printf("%i \n",index); + +} From 720a2a679d5a3cde32c2485a9f6d486d85d15592 Mon Sep 17 00:00:00 2001 From: xliu45 Date: Sat, 5 Mar 2016 13:32:30 -0600 Subject: [PATCH 2/2] Update 162_Find_Peak_Element.cpp --- C/162_Find_Peak_Element.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/C/162_Find_Peak_Element.cpp b/C/162_Find_Peak_Element.cpp index 1d7ebe56..24b30945 100644 --- a/C/162_Find_Peak_Element.cpp +++ b/C/162_Find_Peak_Element.cpp @@ -29,7 +29,7 @@ class Solution { if (nums.at(sz - 1) > nums.at(sz - 2)) return sz - 1; - for(int i = 1; i < nums.size(); i++) + for(int i = 1; i < nums.size()-1; i++) { if (nums.at(i - 1) < nums.at(i) & nums.at(i) > nums.at(i + 1)) return i;