본문 바로가기

C

c++ peak element O(logn)으로 찾기

코드 >>

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
#include <iostream>
#include <vector>
#include <numeric>
 
// Find peak element
 
int peak_ele(std::vector<int>& nums)
{
    
    int left = 0;
    int rightmax = (int)nums.size() - 1;
    int right = (int)nums.size() - 1;
    int pivot = (left + right) / 2;
    int nextValue;
    
    if (nums.size() <= 1)
        return (int)nums[0];
 
    while (left < right)
    {        
        //std::cout << "processing..." << std::endl;
        
        if (pivot != rightmax)
            nextValue = nums[pivot + 1];
        else
        {
            nextValue = nums[(int)nums.size() - 1];
        }
 
        if (nums[pivot] >= nextValue)
        {
            right = pivot;
        }
        else
        {
            left = pivot + 1; }
        
        pivot = (left + right) / 2;
    }
 
    return right;
    
    
}
 
int main()
{
    std::vector<int> nums;
    nums = { 1,2,3,7,4,8 };
    int index = peak_ele(nums);
    std::cout << index << std::endl;
    return 0;
}