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

Posted aaronliu1991

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 34. Find First and Last Position of Element in Sorted Array相关的知识,希望对你有一定的参考价值。

在有序数组中查找元素的第一个和最后一个位置。题意很简单,给了一个数组和一个数字A,问数字A第一次和最后一次在数组中出现的位置在哪里,若没有,return -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]

也是一道典型的二分法题目,思路是通过二分法思想分别找到第一个插入的位置和第二个插入的位置。

时间O(log n)

空间O(1)

 1 /**
 2  * @param {number[]} nums
 3  * @param {number} target
 4  * @return {number[]}
 5  */
 6 var searchRange = function(nums, target) {
 7     // corner case
 8     if (nums === null || nums.length === 0) {
 9         return [-1, -1];
10     }
11     // normal case
12     let start = findFirst(nums, target);
13     if (start === -1) {
14         return [-1, -1];
15     }
16     let end = findLast(nums, target);
17     return [start, end];
18 };
19 
20 var findFirst = function(nums, target) {
21     let start = 0;
22     let end = nums.length - 1;
23     while (start + 1 < end) {
24         let mid = Math.floor(start + (end - start) / 2);
25         if (nums[mid] < target) {
26             start = mid;
27         } else {
28             end = mid;
29         }
30     }
31     if (nums[start] === target) return start;
32     if (nums[end] === target) return end;
33     return -1;
34 };
35 
36 var findLast = function(nums, target) {
37     let start = 0;
38     let end = nums.length - 1;
39     while (start + 1 < end) {
40         let mid = Math.floor(start + (end - start) / 2);
41         if (nums[mid] > target) {
42             end = mid;
43         } else {
44             start = mid;
45         }
46     }
47     if (nums[end] === target) return end;
48     if (nums[start] === target) return start;
49     return -1;
50 };

 

以上是关于[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 解题思路 (python)

[二分搜索] 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

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

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