leetcode Search in Rotated Sorted Array

代码:

 1 #include<iostream>

 2 #include<vector>

 3 

 4 using namespace std;

 5 

 6 int search(vector<int>& nums, int target) 

 7 {

 8     int L = nums.size();

 9     int k = 0;

10     int min = nums[0];

11     for (int i = 1; i < L; i++)

12     {

13         if (nums[i] < min)

14         {

15             min = nums[i];

16             k = i;

17         }

18     }

19     int left, right;

20     if (target>nums[L - 1])

21     {

22         left = 0;

23         right = k - 1;

24     }

25     else

26     {

27         left = k;

28         right = L - 1;

29     }

30     while (left <= right)

31     {

32         int mid = (left + right) / 2;

33         if (target < nums[mid])

34         {

35             right = mid - 1;

36         }

37         else if (target > nums[mid])

38         {

39             left = mid + 1;

40         }

41         else

42         {

43             return mid;

44         }

45     }

46     return -1;

47 }

48 

49 int main()

50 {

51     vector<int> a = {4, 5, 6, 7, 0};

52     cout << search(a, 0) << endl;

53 }

 

你可能感兴趣的:(LeetCode)