Leetcode之javascript解题(No33-34)

附上我的github仓库,会不断更新leetcode解题答案,提供一个思路,大家共勉

在我的主页和github上可以看到更多的关于leetcode的解题报告!(因为不知道为什么掘金没有将其发布出来,目前已经联系掘金客服)

希望可以给star,鼓励继续更新解题思路

author: thomas

No34:Search for Range(Medium)

题目

Given an array of integers 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].

For example

Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4]. // 下标3,4是数组8
复制代码

这道题让我们在一个有序整数数组中寻找相同目标值的起始和结束位置,没如果没有找到就返回[-1,-1]

思路

这道题让我们在一个有序整数数组中寻找相同目标值的起始和结束位置,而且限定了时间复杂度为O(logn),这是典型的二分查找法的时间复杂度,所以这道题我们也需要用此方法。

  • 方法一

    • 我们的思路是对原数组使用两次二分查找法,分别找出一个起始和结束位置
  • 方法二:利用二分法找到起始位置,然后向右遍历,找到边界

代码

  • 方法一
let arr1 = [1,1,2,2,3,4,4,7,8];
let arr = [5,7,7,8,8,10],target = 8;
let searchRange = function(arr, target) {let len = arr.length,res = [-1, -1];for (let i = 0, j = len-1; i <= j;) {let mid = Math.floor((i + j) / 2);if (arr[mid] < target) { // 先判断小于target的情况i = mid + 1;}else {j = mid - 1; // 应对刚好i = mid + 1后就指向了target值if (arr[mid] === target) {res[0] = mid; // 得到起始index}}}for (let i = 0, j = len-1; i <= j;) {let mid = Math.floor((i + j) / 2);if (arr[mid] > target) {// 先判断大于target的情况j = mid - 1;}else {i = mid + 1; // 应对刚好i = mid + 1后就指向了target值if (arr[mid] === target) {res[1] = mid; // 得到结束index}}}return res;
};
console.log(searchRange(arr,target)); // [3, 4]
复制代码
  • 方法二
/*** 方法2** 找到res[0]之后,就向右遍历,直到不是该值,就可以得到右边界了* 时间复杂度没上面的方法好*/let searchRange1 = function(arr, target) {let len = arr.length,res = [-1, -1];for (let i = 0, j = len-1; i <= j;) {let mid = Math.floor((i + j) / 2);if (arr[mid] < target) {i = mid + 1;}else {j = mid - 1; // 应对刚好i = mid + 1后就指向了target值if (arr[mid] === target) {res[0] = mid; // 得到最左边的值}}}let k;res[1] = res[0];for (k = res[0] + 1; k < len; k++) { // 找到右边界if (arr[k] === target) {res[1] += 1;}}return res;
};
console.log(searchRange1([1],1)); // [0, 0]
console.log(searchRange1([2,2],2)); // [0, 1]
console.log(searchRange1([5,7,7,8,8,10],8)); // [3, 4]
console.log(searchRange1([1,3],1)); // [0, 0]
console.log(searchRange1([3,3,3],3)); // [0, 0]
复制代码

注:二分法:其假设我们找到目标值(但是有多个目标值连在一起)

  • 1、如果我们先判断arr[mid] < target(先判断小于target的情况),再判断剩下的,最后得到的结果就是要找的多个目标值target的最左边的值
  • 2、如果我们先判断arr[mid] > target(也就是先判断大于target的情况),再判断剩下的,最后得到的结果就是要找的多个目标值target的最右边的值

No35:Search Insert Position(Easy)

题目

从给定排好顺序的数组,找出给定目标数字下标,存在则返回下标,不存在则返回目标数应该插入的位置下标。 Example 1:

Input: [1,3,5,6], 5
Output: 2
复制代码

Example 2:

Input: [1,3,5,6], 2
Output: 1
复制代码

Example 3:

Input: [1,3,5,6], 7
Output: 4
复制代码

Example 4:

Input: [1,3,5,6], 0
Output: 0
复制代码

思路

思路就是每次取中间,如果等于目标即返回,否则根据大小关系切去一半。因此算法复杂度是O(logn),空间复杂度O(1)

代码

let arr = [1,3,5,6],target = 5;let searchInset = function(arr, target) {let len = arr.length,res = 0;for (let i = 0, j = len -1; i <= j;) {let mid = Math.floor((i+j)/2);if (arr[mid] === target) {return mid;}if (arr[mid] < target) {i = mid + 1;res = mid+1; // 更新res}else {j = mid - 1;}}return res; //
}
console.log(searchInset(arr,target)); // 2
console.log(searchInset([1,3,5,6],2)); // 2
复制代码

注意:二分法有一个好处:就是当循环结束时:

(1)如果找到目标元素,那么就返回当前位置

(2)如果没有找到目标元素,那么i一定停在恰好比目标大的index上,j一定停在恰好比目标小的index上,所以个人比较推荐这种实现方式。(初始i在左,j在右)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/390702.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

真实感人故事_您的数据可以告诉您真实故事吗?

真实感人故事Many are passionate about Data Analytics. Many love matplotlib and Seaborn. Many enjoy designing and working on Classifiers. We are quick to grab a data set and launch Jupyter Notebook, import pandas and NumPy and get to work. But wait a minute…

转:防止跨站攻击,安全过滤

转&#xff1a;http://blog.csdn.net/zpf0918/article/details/43952511 Spring MVC防御CSRF、XSS和SQL注入攻击 本文说一下SpringMVC如何防御CSRF(Cross-site request forgery跨站请求伪造)和XSS(Cross site script跨站脚本攻击)。 说说CSRF 对CSRF来说&#xff0c;其实Spring…

Linux c编程

c语言标准 ANSI CPOSIX&#xff08;提高UNIX程序可移植性&#xff09;SVID&#xff08;POSIX的扩展超集&#xff09;XPG&#xff08;X/Open可移植性指南&#xff09;GNU C&#xff08;唯一能编译Linux内核的编译器&#xff09; gcc 简介 名称&#xff1a; GNU project C an…

html怎么注释掉代码_HTML注释:如何注释掉您HTML代码

html怎么注释掉代码HTML中的注释 (Comments in HTML) The comment tag is an element used to leave notes, mostly related to the project or the website. This tag is frequently used to explain something in the code or leave some recommendations about the project.…

k均值算法 二分k均值算法_使用K均值对加勒比珊瑚礁进行分类

k均值算法 二分k均值算法Have you ever seen a Caribbean reef? Well if you haven’t, prepare yourself.您见过加勒比礁吗&#xff1f; 好吧&#xff0c;如果没有&#xff0c;请做好准备。 Today, we will be answering a question that, at face value, appears quite sim…

您好,这是我的第一篇文章

您好我是CYL 这是一个辣鸡博客 欢迎指教 转载于:https://www.cnblogs.com/pigba/p/8823472.html

08_MySQL DQL_SQL99标准中的多表查询(内连接)

# sql99语法/*语法&#xff1a; select 查询列表 from 表1 别名 【连接类型】 join 表2 别名 on 连接条件 【where 筛选条件】 【group by 分组】 【having 分组后筛选】 【order by 排序列表】分类内连接&#xff08;重点&#xff09;&#xff1a; inner外连接 左外&#xff0…

java中抽象类继承抽象类_Java中的抽象类用示例解释

java中抽象类继承抽象类Abstract classes are classes declared with abstract. They can be subclassed or extended, but cannot be instantiated. You can think of them as a class version of interfaces, or as an interface with actual code attached to the methods.抽…

新建VUX项目

使用Vue-cli安装Vux2 特别注意配置vux-loader。来自为知笔记(Wiz)

衡量试卷难度信度_我们可以通过数字来衡量语言难度吗?

衡量试卷难度信度Without a doubt, the world is “growing smaller” in terms of our access to people and content from other countries and cultures. Even the COVID-19 pandemic, which has curtailed international travel, has led to increasing virtual interactio…

Linux 题目总结

守护进程的工作就是打开一个端口&#xff0c;并且等待&#xff08;Listen&#xff09;进入连接。 如果客户端发起一个连接请求&#xff0c;守护进程就创建&#xff08;Fork&#xff09;一个子进程响应这个连接&#xff0c;而主进程继续监听其他的服务请求。 xinetd能够同时监听…

《精通Spring4.X企业应用开发实战》读后感第二章

一、配置Maven\tomcat https://www.cnblogs.com/Miracle-Maker/articles/6476687.html https://www.cnblogs.com/Knowledge-has-no-limit/p/7240585.html 二、创建数据库表 DROP DATABASE IF EXISTS sampledb; CREATE DATABASE sampledb DEFAULT CHARACTER SET utf8; USE sampl…

换了电脑如何使用hexo继续写博客

前言 我们知道&#xff0c;使用 Githubhexo 搭建一个个人博客确实需要花不少时间的&#xff0c;我们搭好博客后使用的挺好&#xff0c;但是如果我们有一天电脑突然坏了&#xff0c;或者换了系统&#xff0c;那么我们怎么使用 hexo 再发布文章到个人博客呢&#xff1f; 如果我们…

leetcode 525. 连续数组

给定一个二进制数组 nums , 找到含有相同数量的 0 和 1 的最长连续子数组&#xff0c;并返回该子数组的长度。 示例 1: 输入: nums [0,1] 输出: 2 说明: [0, 1] 是具有相同数量 0 和 1 的最长连续子数组。 示例 2: 输入: nums [0,1,0] 输出: 2 说明: [0, 1] (或 [1, 0]) 是…

实践作业2:黑盒测试实践(小组作业)每日任务记录1

会议时间&#xff1a;2017年11月24日20:00 – 20:30 会议地点&#xff1a;在线讨论 主 持 人&#xff1a;王晨懿 参会人员&#xff1a;王晨懿、余晨晨、郑锦波、杨潇、侯欢、汪元 记 录 人&#xff1a;杨潇 会议议题&#xff1a;软件测试课程作业-黑盒测试实践的启动计划 会议内…

视图可视化 后台_如何在单视图中可视化复杂的多层主题

视图可视化 后台Sometimes a dataset can tell many stories. Trying to show them all in a single visualization is great, but can be too much of a good thing. How do you avoid information overload without oversimplification?有时数据集可以讲述许多故事。 试图在…

iam身份验证以及访问控制_如何将受限访问IAM用户添加到EKS群集

iam身份验证以及访问控制介绍 (Introduction) Elastic Kubernetes Service (EKS) is the fully managed Kubernetes service from AWS. It is deeply integrated with many AWS services, such as AWS Identity and Access Management (IAM) (for authentication to the cluste…

一步一步构建自己的管理系统①

2019独角兽企业重金招聘Python工程师标准>>> 系统肯定要先选一个基础框架。 还算比较熟悉Spring. 就选Spring boot postgres mybatis. 前端用Angular. 开始搭开发环境&#xff0c;开在window上整的。 到时候再放到服务器上。 自己也去整了个小服务器&#xff0c;…

面向对象面向过程

1、面向语句&#xff1a; 直接写原生的sql语句&#xff0c;但是这样代码不容易维护。改一个方法会导致整个项目都要改动&#xff0c; 2、面向过程 定义一些函数&#xff0c;用的时候就调用不用就不调用。但是这也有解决不了的问题&#xff0c;如果要维护需要改动代码&#xff0…

python边玩边学_边听边学数据科学

python边玩边学Podcasts are a fun way to learn new stuff about the topics you like. Podcast hosts have to find a way to explain complex ideas in simple terms because no one would understand them otherwise &#x1f642; In this article I present a few episod…