File tree Expand file tree Collapse file tree
search-in-rotated-sorted-array Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int search (int [] nums , int target ) {
3+ int firstIdx = binarySearch (nums );
4+ int result = 0 ;
5+ if (firstIdx == 0 ) {
6+ return binarySearch (target , nums , 0 , nums .length - 1 );
7+ } else if (target >= nums [0 ]) {
8+ return binarySearch (target , nums , 0 , firstIdx );
9+ } else {
10+ return binarySearch (target , nums , firstIdx , nums .length - 1 );
11+ }
12+ }
13+
14+ public int binarySearch (int [] nums ) {
15+ int start = 0 ;
16+ int end = nums .length -1 ;
17+ while (start < end ) {
18+ int mid = (start + end ) / 2 ;
19+ if (nums [mid ] < nums [end ]) {
20+ end = mid ;
21+ } else {
22+ start = mid + 1 ;
23+ }
24+ }
25+ return start ;
26+ }
27+
28+ public int binarySearch (int target , int [] nums , int start , int end ) {
29+ int result = -1 ;
30+ while (start <= end ) {
31+ int mid = (start + end ) / 2 ;
32+ if (nums [mid ] > target ) {
33+ end = mid - 1 ;
34+ } else if (nums [mid ] < target ){
35+ start = mid + 1 ;
36+ } else {
37+ result = mid ;
38+ break ;
39+ }
40+ }
41+
42+ return result ;
43+ }
44+
45+
46+ }
You can’t perform that action at this time.
0 commit comments