Skip to content

Commit f781fa1

Browse files
committed
Sync LeetCode submission - Search in Rotated Sorted Array - Runtime - 0 ms (100.00%), Memory - 17.5 MB (88.32%)
1 parent 42596de commit f781fa1

2 files changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p>
2+
3+
<p>Prior to being passed to your function, <code>nums</code> is <strong>possibly left rotated</strong> at an unknown index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be left rotated by&nbsp;<code>3</code>&nbsp;indices and become <code>[4,5,6,7,0,1,2]</code>.</p>
4+
5+
<p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p>
6+
7+
<p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
<pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0
12+
<strong>Output:</strong> 4
13+
</pre><p><strong class="example">Example 2:</strong></p>
14+
<pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3
15+
<strong>Output:</strong> -1
16+
</pre><p><strong class="example">Example 3:</strong></p>
17+
<pre><strong>Input:</strong> nums = [1], target = 0
18+
<strong>Output:</strong> -1
19+
</pre>
20+
<p>&nbsp;</p>
21+
<p><strong>Constraints:</strong></p>
22+
23+
<ul>
24+
<li><code>1 &lt;= nums.length &lt;= 5000</code></li>
25+
<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
26+
<li>All values of <code>nums</code> are <strong>unique</strong>.</li>
27+
<li><code>nums</code> is an ascending array that is possibly rotated.</li>
28+
<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>
29+
</ul>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def search(self, nums: List[int], target: int) -> int:
3+
4+
left = 0
5+
right = len(nums) - 1
6+
7+
while left <= right:
8+
mid = (left + right) // 2
9+
10+
if nums[mid] == target:
11+
return mid
12+
elif nums[mid] >= nums[left]:
13+
if nums[left] <= target <= nums[mid]:
14+
right = mid - 1
15+
else:
16+
left = mid + 1
17+
else:
18+
if nums[mid] <= target <= nums[right]:
19+
left = mid + 1
20+
else:
21+
right = mid - 1
22+
23+
return -1
24+
25+

0 commit comments

Comments
 (0)