We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent c607b4e commit 29e93bbCopy full SHA for 29e93bb
11 Searching/42 Search in a rotated sorted array.java
@@ -0,0 +1,25 @@
1
+//O(logn) time and O(1) space
2
+class Solution {
3
+ public int search(int[] nums, int target) {
4
+ //Find the original low
5
+ int low = 0,high = nums.length-1;
6
+ while(low<high){
7
+ int mid = low+(high-low)/2;
8
+ if(nums[mid]>nums[high])
9
+ low = mid+1;
10
+ else high = mid;
11
+ }
12
+ //Now low and high has the same value which is equal to the index of the smallest element in the array
13
+ int rot = low;
14
+ low=0;
15
+ high = nums.length-1;
16
+ while(low<=high){
17
18
+ int realmid = (mid+rot)%nums.length;
19
+ if(nums[realmid]==target) return realmid;
20
+ else if(nums[realmid]>target) high = mid-1;
21
+ else low = mid+1;
22
23
+ return -1;
24
25
+}
0 commit comments