Skip to content

Commit e1a756c

Browse files
day9
1 parent 14055fa commit e1a756c

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public int search(int[] nums, int target) {
3+
int left = 0, right = nums.length - 1 ;
4+
while(left <= right){
5+
int mid = (left + right) / 2 ;
6+
if(nums[mid] == target){
7+
return mid;
8+
}
9+
if (nums[left] <= nums[mid]){
10+
if(target >= nums[left] && target < nums[mid]) {
11+
right = mid - 1;
12+
}else{
13+
left = mid + 1;
14+
}
15+
}else{
16+
if(target > nums[mid] && target <= nums[right]){
17+
left = mid + 1;
18+
}else{
19+
right = mid - 1;
20+
}
21+
}
22+
}
23+
return -1;
24+
}
25+
}
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
Link: https://leetcode.com/problems/search-in-rotated-sorted-array/
2+
3+
4+
There is an integer array nums sorted in ascending order (with distinct values).
5+
6+
Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].
7+
8+
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
9+
10+
You must write an algorithm with O(log n) runtime complexity.
11+
12+
13+
14+
Example 1:
15+
16+
Input: nums = [4,5,6,7,0,1,2], target = 0
17+
Output: 4
18+
Example 2:
19+
20+
Input: nums = [4,5,6,7,0,1,2], target = 3
21+
Output: -1
22+
Example 3:
23+
24+
Input: nums = [1], target = 0
25+
Output: -1

0 commit comments

Comments
 (0)