File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed
SearchInRotatedSortedArray33 Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ Suppose a sorted array is rotated at some pivot unknown to you beforehand.
2+
3+ (i.e., ` 0 1 2 4 5 6 7 ` might become ` 4 5 6 7 0 1 2 ` ).
4+
5+ You are given a target value to search. If found in the array return its index, otherwise return -1.
6+
7+ You may assume no duplicate exists in the array.
Original file line number Diff line number Diff line change 1+ public class Solution {
2+ public int search (int [] nums , int target ) {
3+ if (nums == null || nums .length == 0 )
4+ return -1 ;
5+
6+ int left = 0 ;
7+ int right = nums .length - 1 ;
8+
9+ while (left <= right ) {
10+ int mid = (left + right ) >> 1 ;
11+
12+ if (nums [left ] < nums [right ]) {
13+ if (nums [mid ] < target ) {
14+ left = mid + 1 ;
15+ } else if (nums [mid ] > target ) {
16+ right = mid - 1 ;
17+ } else {
18+ return mid ;
19+ }
20+ } else {
21+ if (nums [mid ] < target ) {
22+ if (nums [mid ] < nums [left ]) {
23+ if (nums [left ] < target ) {
24+ right = mid - 1 ;
25+ } else if (nums [left ] > target ) {
26+ left = mid + 1 ;
27+ } else {
28+ return left ;
29+ }
30+ } else {
31+ left = mid + 1 ;
32+ }
33+ } else if (nums [mid ] > target ) {
34+ if (nums [mid ] < nums [left ]) {
35+ right = mid - 1 ;
36+ } else {
37+ if (nums [left ] < target ) {
38+ right = mid - 1 ;
39+ } else if (nums [left ] > target ) {
40+ left = mid + 1 ;
41+ } else {
42+ return left ;
43+ }
44+ }
45+ } else {
46+ return mid ;
47+ }
48+ }
49+ }
50+
51+ return -1 ;
52+ }
53+ }
You can’t perform that action at this time.
0 commit comments