1. 程式人生 > >19.2.2 [LeetCode 34] Find First and Last Position of Element in Sorted Array

19.2.2 [LeetCode 34] Find First and Last Position of Element in Sorted Array

pub urn eve opened leet 分享圖片 sort || end

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]

題意

找已排序數組中某個值的範圍

題解

技術分享圖片
 1 class Solution {
 2 public:
 3     vector<int> searchRange(vector<int>& nums, int target) {
 4         int size = nums.size(), s = 0, e = size - 1;
 5         vector<int>ans;
6 if (size <= 0||target<nums[0]||target>nums[size-1]) { 7 ans.push_back(-1); 8 ans.push_back(-1); 9 return ans; 10 } 11 while (s < e) { 12 int mid = (s + e) / 2; 13 if (nums[mid] < target) 14 s = mid + 1
; 15 else 16 e = mid; 17 } 18 if (nums[s] != target) { 19 ans.push_back(-1); 20 ans.push_back(-1); 21 return ans; 22 } 23 ans.push_back(s); 24 s = 0, e = size - 1; 25 while (s <= e) { 26 int mid = (s + e) / 2; 27 if (nums[mid] <= target) 28 s = mid + 1; 29 else 30 e = mid - 1; 31 } 32 ans.push_back(e); 33 return ans; 34 } 35 };
View Code

兩次二分

19.2.2 [LeetCode 34] Find First and Last Position of Element in Sorted Array