原题目: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. centos7最小安装后无法联网解决方法

    1 进入目录 cd /etc/sysconfig/network-scripts/ # 编辑网卡的配置文件 # 多网卡会对应多个配置文件,均以ifcfg-enp开头 # 新环境配置可任意选择,建议按一 ...

  2. Spring Cloud Ribbon负载均衡(快速搭建)

    Spring Cloud Ribbon 是一个基于HTTP和TCP的客户端负载均衡工具,它基于Netflix Ribbon实现.通过 Spring Cloud 的封装, 可以让我们轻松地将面向服务的 ...

  3. 利用SQL直接生成模型实体类

    在网上找来一个别人写好的,生成实体类的SQL代码 declare @TableName sysname = 'lkxxb' declare @Result varchar(max) = 'public ...

  4. Redis.Memcache和MongoDB区别?

    Memcached的优势: Memcached可以利用多核优势,单吞吐量极高,可以达到几十万QPS(取决于Key.value的字节大小以及服务器硬件性能,日常环境中QPS高峰大约在4-6w左右.)适用 ...

  5. Linux——安装并配置Kafka

    前言 Kafka是由Apache软件基金会开发的一个开源流处理平台,由Scala和Java编写.Kafka是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作流数据. 这种动 ...

  6. C++中的类所占内存空间总结(转)

    类所占内存的大小是由成员变量(静态变量除外)决定的,成员函数(这是笼统的说,后面会细说)是不计算在内的. 摘抄部分: 成员函数还是以一般的函数一样的存在.a.fun()是通过fun(a.this)来调 ...

  7. docker的daemon配置

    文件:/etc/docker/daemon.json,如果没有就创建 修改后重启生效:systemctl restart docker 示例内容: { "registry-mirrors&q ...

  8. AtCoder Beginner Contest 127 解题报告

    传送门 非常遗憾.当天晚上错过这一场.不过感觉也会掉分的吧.后面两题偏结论题,打了的话应该想不出来. A - Ferris Wheel #include <bits/stdc++.h> u ...

  9. 《OKR工作法》——打造一支专一的团队

    <OKR工作法>在最开始讲了这样一个故事,阿塔兰忒是斯巴达跑的最快的人,她的父亲为了将她嫁出去举办了一场跑步比赛并许诺冠军可以娶自己的女儿,阿塔兰忒为了不结婚决定参加比赛自己拿冠军.然而在 ...

  10. Xamarin开发及学习资源

    入行文章指引 移动开发下Xamarin VS PhoneGap 跨平台开发 许多企业希望能够通过开发移动应用程序,来提升企业业务水平,开发原生App时往往又缺少专业的Objective C 或 Jav ...