[Swift]LeetCode74. 搜索二維矩陣 | Search a 2D Matrix

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公眾號:山青詠芝(shanqingyongzhi)
?博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
?GitHub地址:https://github.com/strengthen/LeetCode
?原文地址:https://www.cnblogs.com/strengthen/p/9929505.html?
?如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
?原文已修改更新!強烈建議點擊原文地址閱讀!支持作者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Write an efficient algorithm that searches for a value in an?m?x?n?matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

Example 1:

Input:
matrix = [[1,   3,  5,  7],[10, 11, 16, 20],[23, 30, 34, 50]
]
target = 3
Output: true

Example 2:

Input:
matrix = [[1,   3,  5,  7],[10, 11, 16, 20],[23, 30, 34, 50]
]
target = 13
Output: false

編寫一個高效的算法來判斷?m?x?n?矩陣中,是否存在一個目標值。該矩陣具有如下特性:

  • 每行中的整數從左到右按升序排列。
  • 每行的第一個整數大于前一行的最后一個整數。

示例?1:

輸入:
matrix = [[1,   3,  5,  7],[10, 11, 16, 20],[23, 30, 34, 50]
]
target = 3
輸出: true

示例?2:

輸入:
matrix = [[1,   3,  5,  7],[10, 11, 16, 20],[23, 30, 34, 50]
]
target = 13
輸出: false

16ms
 1 class Solution {
 2     func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
 3         guard matrix.count > 0 else {
 4             return false
 5         }
 6         
 7         let rows = matrix.count
 8         let columns = matrix[0].count
 9         
10         var first = 0
11         var last = rows*columns-1
12         
13         while first <= last {
14             let mid = first + (last-first)/2
15             
16             if matrix[mid/columns][mid%columns] == target {
17                 return true
18             }
19             
20             if matrix[mid/columns][mid%columns] > target {
21                 last = mid-1
22             }
23             else {
24                 first = mid+1
25             }
26         }
27         
28         return false
29     }
30 }

16ms

 1 class Solution {
 2     func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
 3         if matrix.count == 0 || matrix[0].count == 0 {
 4             return false
 5         }
 6 
 7         let n = matrix.count
 8         let m = matrix[0].count
 9         var left = 0
10         var right = m * n - 1
11 
12         while left < right {
13             let middle = left + (right - left - 1) / 2
14             if matrix[middle / m][middle % m] < target {
15                 left = middle + 1
16             } else {
17                 right = middle
18             }
19         }
20 
21         return matrix[right / m][right % m] == target
22     }
23 }

20ms

 1 class Solution {
 2     func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
 3         if matrix.count == 0 || matrix.first!.count <= 0 {
 4             return false
 5         }
 6         // 邊界判斷
 7         if target < matrix.first!.first! || target > matrix.last!.last! {
 8             return false
 9         }
10         // 因為矩陣的每行都有序, 可將矩陣看作"一個數組"進行二分查找
11         var low = 0
12         var high = matrix.count * matrix.first!.count - 1
13         var mid = 0
14         while low <= high {
15             mid = (low + high) / 2
16             let coords = convertIndex(mid, in: matrix) // index轉換為坐標
17             let value = matrix[coords.row][coords.column]
18             if value == target {
19                 return true
20             } else if target < value {
21                 high = mid - 1
22             } else {
23                 low = mid + 1
24             }
25         }
26         return false
27     }
28     
29     private func convertIndex(_ index: Int, in matix: [[Any]]) -> (row: Int, column: Int) {
30         return (row: index / matix.first!.count,
31                 column: index % matix.first!.count)
32     }
33 }

80ms

 1 class Solution {
 2     func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
 3         guard !matrix.isEmpty else { return false }
 4 
 5         let lastRowIndex = matrix.count - 1
 6 
 7         for (index, row) in matrix.enumerated() {
 8             guard !row.isEmpty else { continue }
 9             guard target >= row[0] else { continue }
10 
11             if lastRowIndex != index && target >= matrix[index + 1][0] {
12                 continue
13             }
14 
15             for n in row {
16                 if n == target {
17                     return true
18                 }
19             }
20 
21         }
22 
23         return false
24     }
25 }

100ms

 1 class Solution {
 2     func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
 3         let arr = matrix.flatMap{$0}
 4         return binarySearch(arr, 0, arr.count - 1, target)
 5     }
 6     
 7     func binarySearch(_ arr: [Int], _ start: Int, _ end: Int, _ target: Int) -> Bool {
 8         let mid = (start + end ) / 2
 9         guard start <= end else { return false }
10         if target == arr[mid] { return true}
11         if target < arr[mid] {
12             return binarySearch(arr, start, mid - 1, target)
13         } else {
14             return binarySearch(arr,  mid + 1, end, target)
15         }
16     }
17 }

104ms

 1 class Solution {
 2     func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
 3         let arr = matrix.flatMap{$0}
 4         return binarySearch(arr, 0, arr.count - 1, target)
 5     }
 6     
 7     func divide(_ arr: [[Int]], _ start: Int, _ end:Int, _ target: Int) -> Bool {
 8         guard start <= end else { return false }
 9         if start == end {
10             return binarySearch(arr[start], 0, arr[start].count - 1, target)
11         }
12         
13         let mid = (start + end ) / 2
14         let localArr = arr[mid]
15         let high = localArr[localArr.count - 1]
16         if target == high { return true}
17         if high < target {
18             return divide(arr, mid + 1, end, target)
19         } else {
20              return divide(arr, start, mid, target)
21         }
22     }
23     
24     func binarySearch(_ arr: [Int], _ start: Int, _ end: Int, _ target: Int) -> Bool {
25         let mid = (start + end ) / 2
26         guard start <= end else { return false }
27         if target == arr[mid] { return true}
28         if target < arr[mid] {
29             return binarySearch(arr, start, mid - 1, target)
30         } else {
31             return binarySearch(arr,  mid + 1, end, target)
32         }
33     }
34 }

?

轉載于:https://www.cnblogs.com/strengthen/p/9929505.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388040.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388040.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388040.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

iris數據集 測試集_IRIS數據集的探索性數據分析

iris數據集 測試集Let’s explore one of the simplest datasets, The IRIS Dataset which basically is a data about three species of a Flower type in form of its sepal length, sepal width, petal length, and petal width. The data set consists of 50 samples from …

Oracle 12c 安裝 Linuxx86_64

1)下載Oracle Database 12cRelease 1安裝介質 官方的下載地址&#xff1a; 1&#xff1a;http://www.oracle.com/technetwork/database/enterprise-edition/downloads/index.html 2&#xff1a;https://edelivery.oracle.com/EPD/Download/get_form?egroup_aru_number16496…

Linux入門實驗

學習Linux要先做實驗來熟悉操作系統本次先寫點入門的操作。 關于Linux入門實驗的操作如下&#xff1a; 【例1】顯示當前使用的shell [rootcentos7 ~]# echo ${SHELL} /bin/bash 【例2】顯示當前系統使用的所有shell [rootcentos7 ~]#cat /etc/shells /bin/sh /bin/bash /usr/bi…

flink 檢查點_Flink檢查點和恢復

flink 檢查點Apache Flink is a popular real-time data processing framework. It’s gaining more and more popularity thanks to its low-latency processing at extremely high throughput in a fault-tolerant manner.Apache Flink是一種流行的實時數據處理框架。 它以容…

917. 僅僅反轉字母

給定一個字符串 S&#xff0c;返回 “反轉后的” 字符串&#xff0c;其中不是字母的字符都保留在原地&#xff0c;而所有字母的位置發生反轉。 示例 1&#xff1a; 輸入&#xff1a;"ab-cd" 輸出&#xff1a;"dc-ba"示例 2&#xff1a; 輸入&#xff1a;&q…

C# socket nat 映射 網絡 代理 轉發

using System;using System.Collections.Generic;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;namespace portmap_net{/// <summary>/// 映射器實例狀態/// </summary>sealed internal class state{#region Fields (5)pu…

python初學者_初學者使用Python的完整介紹

python初學者A magical art of teaching a computer to perform a task is called computer programming. Programming is one of the most valuable skills to have in this competitive world of computers. We, as modern humans, are living with lots of gadgets such as …

c# nat udp轉發

UdpClient myClient;Thread recvThread;//打開udp端口開始接收private void startRecv(int port){myClient new UdpClient(port);recvThread new Thread(new ThreadStart(receive));recvThread.Start();}//停止接收private void stopRecv(){recvThread.Abort();}private void…

【Code-Snippet】TextView

1. TextView文字過長&#xff0c;顯示省略號 【參考】 必須要同時設置XML和JAVA&#xff0c;而且&#xff0c;java中設置文字必須是在最后。 android:ellipsize"start|end|middle" //省略號的位置 android:singleLine"true" android:lines"2"…

Object 的靜態方法之 defineProperties 以及數據劫持效果

再提一下什么是靜態方法&#xff1a; 靜態方法&#xff1a;在類身上的方法&#xff0c;  動態方法:在實例身上的方法 Object.defineProperties(obj, props)obj&#xff1a;被添加屬性的對象props&#xff1a;添加或更新的屬性對象給對象定義屬性&#xff0c;如果存在該屬性&a…

Spring實現AOP的4種方式

Spring實現AOP的4種方式 先了解AOP的相關術語: 1.通知(Advice): 通知定義了切面是什么以及何時使用。描述了切面要完成的工作和何時需要執行這個工作。 2.連接點(Joinpoint): 程序能夠應用通知的一個“時機”&#xff0c;這些“時機”就是連接點&#xff0c;例如方法被調用時、…

如何使用Plotly在Python中為任何DataFrame繪制地圖的衛星視圖

Chart-Studio和Mapbox簡介 (Introduction to Chart-Studio and Mapbox) Folium and Geemap are arguably the best GIS libraries/tools to plot satellite-view maps or any other kinds out there, but at times they require an additional authorization to use the Google…

Java入門系列-26-JDBC

認識 JDBC JDBC (Java DataBase Connectivity) 是 Java 數據庫連接技術的簡稱&#xff0c;用于連接常用數據庫。 Sun 公司提供了 JDBC API &#xff0c;供程序員調用接口和類&#xff0c;集成在 java.sql 和 javax.sql 包中。 Sun 公司還提供了 DriverManager 類用來管理各種不…

3.19PMP試題每日一題

在房屋建造過程中&#xff0c;應該先完成衛生管道工程&#xff0c;才能進行電氣工程施工&#xff0c;這是一個&#xff1a;A、強制性依賴關系B、選擇性依賴關系C、外部依賴關系D、內部依賴關系 作者&#xff1a;Tracy19890201&#xff08;同微信號&#xff09;轉載于:https://…

Can't find temporary directory:internal error

今天我機子上的SVN突然沒有辦法進行代碼提交了&#xff0c;出現的錯誤提示信息為&#xff1a; Error&#xff1a;Cant find temporary directory:internal error 然后試了下其他的SVN源&#xff0c;發現均無法提交&#xff0c;并且update時也出現上面的錯誤信息。對比項目文件…

snowflake 數據庫_Snowflake數據分析教程

snowflake 數據庫目錄 (Table of Contents) Introduction 介紹 Creating a Snowflake Datasource 創建雪花數據源 Querying Your Datasource 查詢數據源 Analyzing Your Data and Adding Visualizations 分析數據并添加可視化 Using Drilldowns on Your Visualizations 在可視化…

jeesite緩存問題

jeesite&#xff0c;其框架主要為&#xff1a; 后端 核心框架&#xff1a;Spring Framework 4.0 安全框架&#xff1a;Apache Shiro 1.2 視圖框架&#xff1a;Spring MVC 4.0 服務端驗證&#xff1a;Hibernate Validator 5.1 布局框架&#xff1a;SiteMesh 2.4 工作流引擎…

高級Python:定義類時要應用的9種最佳做法

重點 (Top highlight)At its core, Python is an object-oriented programming (OOP) language. Being an OOP language, Python handles data and functionalities by supporting various features centered around objects. For instance, data structures are all objects, …

Java 注解 攔截器

場景描述&#xff1a;現在需要對部分Controller或者Controller里面的服務方法進行權限攔截。如果存在我們自定義的注解&#xff0c;通過自定義注解提取所需的權限值&#xff0c;然后對比session中的權限判斷當前用戶是否具有對該控制器或控制器方法的訪問權限。如果沒有相關權限…

醫療大數據處理流程_我們需要數據來大規模改善醫療流程

醫療大數據處理流程Note: the fictitious examples and diagrams are for illustrative purposes ONLY. They are mainly simplifications of real phenomena. Please consult with your physician if you have any questions.注意&#xff1a;虛擬示例和圖表僅用于說明目的。 …