-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path81.cpp
More file actions
108 lines (90 loc) · 2.44 KB
/
81.cpp
File metadata and controls
108 lines (90 loc) · 2.44 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Author : Accagain
// Date : 17/4/11
// Email : chenmaosen0@gmail.com
/***************************************************************************************
*
* 题意:
* Follow up for "Search in Rotated Sorted Array":
*
* What if duplicates are allowed?
*
* Would this affect the run-time complexity? How and why?
*
* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
*
* (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
*
* Write a function to determine if a given target is in the array.
*
* The array may contain duplicates.
*
* 做法:
*
* 时间复杂度:
*
*
****************************************************************************************/
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#define INF 0x3fffffff
using namespace std;
class Solution {
public:
int search(vector<int> &nums, int target) {
if(nums.size() == 0)
{
return false;
}
int l = 0, r = nums.size() - 1;
int ans = -1;
int same[nums.size()];
int last = -INF, re = -1;
for(int i=0; i<r; i++)
{
if (nums[i] != last)
{
last = nums[i];
re = i;
same[i] = i;
}
else
{
same[i] = re;
}
printf("%d ", same[i]);
}
while (l <= r) {
int mid = (l + r) / 2;
//printf("%d %d\n", mid, nums[mid]);
if (target == nums[mid]) {
ans = mid;
break;
} else if ((nums[l] < nums[mid]) || ((nums[l] == nums[mid]) && (same[mid] <= l))) { //怎样确定是左边
// 2 2 2 2 1 1 2 的情况确定
if (target >= nums[l] && target < nums[mid])
r = mid - 1;
else
l = mid + 1;
} else {
if (target > nums[mid] && target <= nums[r])
l = mid + 1;
else
r = mid - 1;
}
}
return ans == -1 ? false : true;
}
};
int main() {
Solution *test = new Solution();
int data[] = {1, 1, 3, 1, 1, 1, 1};
vector<int> x(data, data + sizeof(data) / sizeof(data[0]));
printf("%d\n", test->search(x, 3));
return 0;
}
//
// Created by cms on 17/4/11.
//