作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/description/

题目描述

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]

题目大意

在一个数组中,找出某个target值开始的最左边和最右边的索引,如果target不存在,那么就返回[-1, -1]。

解题方法

二分查找

本来见到这个题,第一感觉肯定就是二分查找左右区间,并且题目很明显的说了O(logn)的时间复杂度,那么明显就是要求使用二分。

题目要求找到开始的索引和结束索引,所以就是C++的lower_bound和upper_bound。代码我觉得应该是要背下来的,这两个函数只有一点不同,就是nums[mid]与target的判断,lower_bound倾向于找左边的元素,所以只有nums[mid] < target时才移动左指针;而upper_bound倾向于找右边的元素,所以当nums[mid] <= target就向右移动左指针了。

lower_bound返回的是开始的第一个满足条件的位置,而upper_bound返回的是第一个不满足条件的位置。所以,当两个相等的时候代表没有找到,如果找到了的话,需要返回的是[left, right - 1].

时间复杂度是O(logn),空间复杂度是O(1).超过了100%的提交。

class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left = self.lowwer_bound(nums, target)
right = self.higher_bound(nums, target)
if left == right:
return [-1, -1]
return [left, right - 1] def lowwer_bound(self, nums, target):
# find in range [left, right)
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) / 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
return left def higher_bound(self, nums, target):
# find in range [left, right)
left, right = 0, len(nums)
while left < right:
mid = left + (right - left) / 2
if nums[mid] <= target:
left = mid + 1
else:
right = mid
return left

其实,在python中有封装好的二分查找模块,就是bisect模块。我第一个提交就是使用这个模块快速写出来提交的,如果是比赛的话尽量用别人封装好的。

时间复杂度是O(logn),空间复杂度是O(1).超过了100%的提交。

class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
left = bisect.bisect_left(nums, target)
right = bisect.bisect_right(nums, target)
if left == right:
return [-1, -1]
return [left, right - 1]

C++代码自己手写lower_bound和upper_bound函数如下:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int low = lower_bound(nums, target);
int high = upper_bound(nums, target);
if (low == high)
return {-1, -1};
else
return {low, high - 1};
}
int lower_bound(vector<int>& nums, int target) {
const int N = nums.size();
// [l, r)
int l = 0, r = N;
while (l < r) {
int mid = l + (r - l) / 2;
if (nums[mid] >= target) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
}
int upper_bound(vector<int>& nums, int target) {
const int N = nums.size();
// [l, r)
int l = 0, r = N;
while (l < r) {
int mid = l + (r - l) / 2;
if (nums[mid] <= target) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}
};

C++代码使用lower_bound()和upper_bound()函数的代码如下:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto low = lower_bound(nums.begin(), nums.end(), target);
auto high = upper_bound(nums.begin(), nums.end(), target);
if (low == high) return {-1, -1};
return {low - nums.begin(), high - nums.begin() - 1};
}
};

日期

2018 年 10 月 21 日 —— 新的一周又开始了
2019 年 1 月 11 日 —— 小光棍节?

【LeetCode】34. Find First and Last Position of Element in Sorted Array 解题报告(Python & C++)的更多相关文章

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

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

  2. [LeetCode] 34. Find First and Last Position of Element in Sorted Array == [LintCode] 61. Search for a Range_Easy tag: Binary Search

    Description Given a sorted array of n integers, find the starting and ending position of a given tar ...

  3. [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 ...

  4. (二分查找 拓展) leetcode 34. Find First and Last Position of Element in Sorted Array && lintcode 61. Search for a Range

    Given an array of integers nums sorted in ascending order, find the starting and ending position of ...

  5. [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 ...

  6. 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 ...

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

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

  8. 【LeetCode】26. Remove Duplicates from Sorted Array 解题报告(Python&C++&Java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双指针 日期 [LeetCode] https:// ...

  9. leetcode个人题解——#34 Find First and Last Position of Element in Sorted Array

    思路:先二分查找到一个和target相同的元素,然后再左边二分查找左边界,右边二分查找有边界. class Solution { public: , end = -; int ends; int lS ...

随机推荐

  1. R语言与医学统计图形-【19】ggplot2坐标轴调节

    ggplot2绘图系统--坐标轴调节 scale函数:图形遥控器.坐标轴标度函数: scale_x_continous scale_y_continous scale_x_discrete scale ...

  2. 简单mvc框架核心笔记

    简单mvc框架核心笔记 看了thinkphp5的源码,模仿写了一个简单的框架,有一些心得笔记,记录一下 1.目录结构 比较简单,没有tp那么复杂,只是把需要的核心类写了一些. 核心类库放在mykj里, ...

  3. 关于vim复制剪贴粘贴命令的总结-转

    最近在使用vim,感觉很好很强大,但是在使用复制剪切粘贴命令是,碰到了一些小困惑,网上找了一些资料感觉很不全,讲的也不好,遂自己进行实践并总结了. 首先是剪切(删除): 剪切其实也就顺带删除了所选择的 ...

  4. C++ 中的多重继承的问题

    如何正确使用C++多重继承 BY R12F · PUBLISHED 2011年06月17日 · UPDATED 2012年03月11日   原创文章,转载请注明:转载自Soul Apogee本文链接地 ...

  5. TensorFlow 2.0 深度学习实战 —— 浅谈卷积神经网络 CNN

    前言 上一章为大家介绍过深度学习的基础和多层感知机 MLP 的应用,本章开始将深入讲解卷积神经网络的实用场景.卷积神经网络 CNN(Convolutional Neural Networks,Conv ...

  6. Flume对接Kafka

    目录 一.简单实现 1)flume的配置文件 二.自定义interceptor(使用kafka sink) 1)自定义 flume 拦截器 2)编写 flume 的配置文件 3)创建topic 4)启 ...

  7. 零基础学习java------day3-运算符 以及eclipse的使用

    今日内容: 1. 算数运算符 2. 赋值运算符 3. 关系运算符 4. 逻辑运算符 5. 位运算符 6.三目运算符 一 运算符 运算:对常量和变量进行操作的过程称为运算 运算符:对常量和变量进行操作的 ...

  8. Linux学习 - 数值运算

    1 declare 声明变量类型 declare [+/-] [选项] 变量名 - 给变量设定类型属性 + 取消变量的类型属性 -i 将变量声明为整数型 -x 将变量声明为环境变量(同export) ...

  9. OS开发之Objective-C与JavaScript的交互

    UIWebView是iOS最常用的SDK之一,它有一个stringByEvaluatingJavaScriptFromString方法可以将javascript嵌入页面中,通过这个方法我们可以在iOS ...

  10. centos7.4 64位安装 redis-4.0.0

    1.  下载 redis 包 链接:https://pan.baidu.com/s/1g1UE_GTreXoD9uOXB7G3HA 提取码:ug8p 2. 安装gcc.ruby .rubygems等环 ...