반응형
Problem
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Example 1:
Input: nums = [5,7,7,8,8,10]
, target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10]
, target = 6
Output: [-1,-1]
Solution
- Approach 1 : Linear Scan
Checking every index for target exhausts the search space, so it must work.
But its time complexity is \(O(n)\).
- Approach 2 : Binary Search
Because the array is sorted, we can use binary search to locate the left and rightmost indices.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | class Solution: def searchRange(self, nums, target) : n = len(nums) if n == 0 or (n==1 and target != nums[0]): return [-1, -1] def search(arr, t): l, r = 0, len(arr) while l<r : mid = (l+r)//2 num = arr[mid] if num < t : l = mid+1 else : r = mid return l start = search(nums, target) if start >= n or target != nums[start] : return [-1, -1] end = start + search(nums[start:], target+1)-1 return [start, end] | cs |
Complexity Analysis
•Time complexity : \(O(logn)\)
•Space complexity : \(O(1)\). All work is done in place, so the overall memory usage is constant.
Source
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
반응형
'0 > algorithm' 카테고리의 다른 글
Permutations (in Python) (0) | 2019.01.23 |
---|---|
Spiral Matrix (in Python) (0) | 2019.01.23 |
Next Permutation (in Python) (0) | 2019.01.21 |
Swap Nodes in Pairs (in Python) (0) | 2019.01.21 |
Generate Parentheses (in Python) (0) | 2019.01.21 |