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

Posted TobicYAL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.2.2 [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]

题意

找已排序数组中某个值的范围

题解

技术图片
 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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 34. Find First and Last Position of Element in Sorted Array

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

LeetCode 34. Find First and Last Position of Element in Sorted Array

[二分搜索] leetcode 34 Find First and Last Position of Element in Sorted Array

[Leetcode] 564. Find the Closest Palindrome 解题报告

[Lintcode]61. Search for a Range/[Leetcode]34. Find First and Last Position of Element in Sorted Arr