-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path34.在排序数组中查找元素的第一个和最后一个位置.js
More file actions
63 lines (61 loc) · 1.29 KB
/
34.在排序数组中查找元素的第一个和最后一个位置.js
File metadata and controls
63 lines (61 loc) · 1.29 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。
//
// 如果数组中不存在目标值 target,返回 [-1, -1]。
//
// 你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。
//
//
//
// 示例 1:
//
//
//输入:nums = [5,7,7,8,8,10], target = 8
//输出:[3,4]
//
// 示例 2:
//
//
//输入:nums = [5,7,7,8,8,10], target = 6
//输出:[-1,-1]
//
// 示例 3:
//
//
//输入:nums = [], target = 0
//输出:[-1,-1]
//
//
//
// 提示:
//
//
// 0 <= nums.length <= 10⁵
// -10⁹ <= nums[i] <= 10⁹
// nums 是一个非递减数组
// -10⁹ <= target <= 10⁹
//
//
// Related Topics 数组 二分查找 👍 1875 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var searchRange = function(nums, target) {
const result = [-1, -1]
for(let i = 0; i< nums.length; i++) {
if(nums[i] === target) {
result[0] = i
break
}
}
for(let i = nums.length - 1; i >= 0; i--) {
if(nums[i] === target) {
result[1] = i
break
}
}
return result
};
//leetcode submit region end(Prohibit modification and deletion)