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.pswp.cn/news/390702.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390702.shtml
英文地址,請注明出處:http://en.pswp.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…