Leetcode 34 Find First and Last Position of Element in Sorted Array
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]
這個題的意思是在一個陣列中尋找與target相等的兩個數並返回位置,要求時間複雜度為O(Log n),則可以看出使用二分法進行求,但是需要做一點變形,因為兩個數字相等的時候不適合二分。
1)
class Solution {
public int[] searchRange(int[] nums, int target) {
double left = target - 0.5, right = target + 0.5;
int l = bs(nums, left), r = bs(nums, right);
if(l == r) return new int[]{-1, -1};
return new int[]{l, r-1};
}
public int bs(int[] nums, double target) {
int l = 0, h = nums.length-1;
while(l <= h){
int m = l + (h - l)/2;
if(target > nums[m]) l = m+1;
else h = m-1;
}
return l;
}
}
相關文章
- [LeetCode] Find First and Last Position of Element in SortedLeetCodeAST
- [LeetCode] 3011. Find if Array Can Be SortedLeetCode
- LeetCode | 153. Find Minimum in Rotated Sorted ArrayLeetCode
- Find Minimum in Rotated Sorted Array I & II
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- LeetCode之Squares of a Sorted Array(Kotlin)LeetCodeKotlin
- Leetcode 88. Merge Sorted ArrayLeetCode
- Leetcode 26 Remove Duplicates from Sorted ArrayLeetCodeREM
- LeetCode Kth Largest Element in an ArrayLeetCode
- [LeetCode] 702. Search in a Sorted Array of Unknown SizeLeetCode
- [leetcode]convert-sorted-array-to-binary-search-treeLeetCode
- [leetcode]remove-duplicates-from-sorted-array-iiLeetCodeREM
- Leetcode 442. Find All Duplicates in an ArrayLeetCode
- [leetcode] 1394. Find Lucky Integer in an ArrayLeetCode
- [LeetCode] 378. Kth Smallest Element in a Sorted MatrixLeetCode
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode
- [LeetCode] 80. Remove Duplicates from Sorted Array IILeetCodeREM
- LeetCode 448. Find All Numbers Disappeared in an ArrayLeetCodeAPP
- python leetcode 215. Kth Largest Element in an ArrayPythonLeetCode
- # Search in Rotated Sorted Array
- LeetCode C++ 33. Search in Rotated Sorted Array【二分】中等LeetCodeC++
- 88. Merge Sorted Array
- 977. Squares of a Sorted Array
- B. Find The Array
- 【刷題】Search in a Big Sorted Array
- Remove-duplicates-from-sorted-arrayREM
- LeetCode之N-Repeated Element in Size 2N Array(Kotlin)LeetCodeKotlin
- Find All Numbers Disappeared in an ArrayAPP
- 【leetcode】26. Remove Duplicates from Sorted Array 刪除有序陣列的重複元素LeetCodeREM陣列
- [leetcode]length-of-last-wordLeetCodeAST
- 108-Convert Sorted Array to Binary Search Tree
- 162. Find Peak Element
- Leetcode 35 Search Insert PositionLeetCode
- Leetcode Sort ArrayLeetCode
- Oracle分析函式-first_value()和last_value()Oracle函式AST
- 【Leetcode】1046. Last Stone WeightLeetCodeAST
- Leetcode 41 First Missing PositiveLeetCode
- 215. Kth Largest Element in an Array