原题目:Search for a Range, 现在题目改为: 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]

给一个有序整数数组中,寻找相同目标值的起始和结束位置,限定了时间复杂度为O(logn)。

解法:二分法,典型的二分查找法的时间复杂度,先对原数组使用二分查找法,找出其中一个目标值的位置,然后向两边搜索找出起始和结束的位置。

Java:

public class Solution {
public int[] searchRange(int[] A, int target) {
int start = Solution.firstGreaterEqual(A, target);
if (start == A.length || A[start] != target) {
return new int[]{-1, -1};
}
return new int[]{start, Solution.firstGreaterEqual(A, target + 1) - 1};
} //find the first number that is greater than or equal to target.
//could return A.length if target is greater than A[A.length-1].
//actually this is the same as lower_bound in C++ STL.
private static int firstGreaterEqual(int[] A, int target) {
int low = 0, high = A.length;
while (low < high) {
int mid = low + ((high - low) >> 1);
//low <= mid < high
if (A[mid] < target) {
low = mid + 1;
} else {
//should not be mid-1 when A[mid]==target.
//could be mid even if A[mid]>target because mid<high.
high = mid;
}
}
return low;
}
}  

Python:

class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# Find the first idx where nums[idx] >= target
left = self.binarySearch(lambda x, y: x >= y, nums, target)
if left >= len(nums) or nums[left] != target:
return [-1, -1]
# Find the first idx where nums[idx] > target
right = self.binarySearch(lambda x, y: x > y, nums, target)
return [left, right - 1] def binarySearch(self, compare, nums, target):
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid
else:
left = mid + 1
return left def binarySearch2(self, compare, nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid - 1
else:
left = mid + 1
return left def binarySearch3(self, compare, nums, target):
left, right = -1, len(nums)
while left + 1 < right:
mid = left + (right - left) / 2
if compare(nums[mid], target):
right = mid
else:
left = mid
return left if left != -1 and compare(nums[left], target) else right

C++:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
const auto start = lower_bound(nums.cbegin(), nums.cend(), target);
const auto end = upper_bound(nums.cbegin(), nums.cend(), target);
if (start != nums.cend() && *start == target) {
return {start - nums.cbegin(), end - nums.cbegin() - 1};
}
return {-1, -1};
}
}; class Solution2 {
public:
vector<int> searchRange(vector<int> &nums, int target) {
const int begin = lower_bound(nums, target);
const int end = upper_bound(nums, target); if (begin < nums.size() && nums[begin] == target) {
return {begin, end - 1};
} return {-1, -1};
} private:
int lower_bound(vector<int> &nums, int target) {
int left = 0;
int right = nums.size();
// Find min left s.t. A[left] >= target.
while (left < right) {
const auto mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
} int upper_bound(vector<int> &nums, int target) {
int left = 0;
int right = nums.size();
// Find min left s.t. A[left] > target.
while (left < right) {
const auto mid = left + (right - left) / 2;
if (nums[mid] > target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};

  

  

All LeetCode Questions List 题目汇总

[LeetCode] 34. Search for a Range 搜索一个范围(Find First and Last Position of Element in Sorted Array)的更多相关文章

  1. [Swift]LeetCode34. 在排序数组中查找元素的第一个和最后一个位置 | 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 ...

  2. [array] leetcode - 34. Search for a Range - Medium

    leetcode - 34. Search for a Range - Medium descrition Given an array of integers sorted in ascending ...

  3. Leetcode 34 Find First and Last Position of Element in Sorted Array 解题思路 (python)

    本人编程小白,如果有写的不对.或者能更完善的地方请个位批评指正! 这个是leetcode的第34题,这道题的tag是数组,需要用到二分搜索法来解答 34. Find First and Last Po ...

  4. 乘风破浪:LeetCode真题_034_Find First and Last Position of Element in Sorted Array

    乘风破浪:LeetCode真题_034_Find First and Last Position of Element in Sorted Array 一.前言 这次我们还是要改造二分搜索,但是想法却 ...

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

    目录 题目链接 注意点 解法 小结 题目链接 Find First and Last Position of Element in Sorted Array - LeetCode 注意点 nums可能 ...

  6. 刷题34. Find First and Last Position of Element in Sorted Array

    一.题目说明 题目是34. Find First and Last Position of Element in Sorted Array,查找一个给定值的起止位置,时间复杂度要求是Olog(n).题 ...

  7. [LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  8. leetCode 34.Search for a Range (搜索范围) 解题思路和方法

    Search for a Range Given a sorted array of integers, find the starting and ending position of a give ...

  9. leetcode@ [34] Search for a Range (STL Binary Search)

    https://leetcode.com/problems/search-for-a-range/ Given a sorted array of integers, find the startin ...

随机推荐

  1. python测试开发django-58.MySQL server has gone away错误的解决办法

    前言 使用django执行sql相关操作的时候,出现一个"MySQL server has gone away"错误,后来查了下是sql执行过程中,导入的文件较大时候,会出现这个异 ...

  2. 8、Python简单数据类型(int、float、complex、bool、str)

    一.数据类型分类 1.按存值个数区分 单个值:数字,字符串 多个值(容器):列表,元组,字典,集合 2.按可变不可变区分 可变:列表[],字典{},集合{} 不可变:数字,字符串,元组().bool, ...

  3. centos7部署etcd集群

    实验环境:centos7.4纯净版 192.168.216.130 node1 master 192.168.216.132 node2 slave 192.168.216.134 node3 sla ...

  4. Fiddler抓包工具介绍

    Fiddler官网 https://www.telerik.com/download/fiddler Fiddler原理 当你打开Fiddler工具的时候你会发现你浏览器的代理服务器被添加了127.0 ...

  5. 洛谷 SP338 ROADS - Roads 题解

    思路 dfs(只不过要用邻接表存)邻接表是由表头结点和表结点两部分组成,其中表头结点存储图的各顶点,表结点用单向链表存储表头结点所对应顶点的相邻顶点(也就是表示了图的边).在有向图里表示表头结点指向其 ...

  6. linux学习8 运维基本功-Linux获取命令使用帮助详解

    一.Linux基础知识 1.人机交互界面: a.GUI b.CLI:[login@hostname workdir]# COMMAND 2.命令知识 通用格式:# COMMAND  OPTIONS A ...

  7. BZOJ 5338: [TJOI2018]xor 可持久化trie+dfs序

    强行把序列问题放树上,好无聊啊~ code: #include <bits/stdc++.h> #define N 200005 #define setIO(s) freopen(s&qu ...

  8. WinDbg常用命令系列---|(进程状态)

    |(进程状态) 简介 (|) 命令显示指定进程的状态或当前正在调试你的所有进程. 使用形式 | Process 参数 Process 指定要显示的进程. 如果省略此参数,将显示所有正在调试的进程. 支 ...

  9. globing通配符

    匹配标点符号 linux中只要不含有/的文件就可以生成,所以标点符号也是符合要求的 匹配空白 使用\对空白进行转义,这样就可以生成包含空格名称的文件 但是不推荐这样用,容易让别人在使用的时候造成误解 ...

  10. CTF入门(一)

    ctf入门指南 如何入门?如何组队? capture the flag 夺旗比赛 类型: Web密码学pwn 程序的逻辑分析,漏洞利用windows.linux.小型机等misc 杂项,隐写,数据还原 ...