Skip to content

feat: add swift implementation to lcci problem: No.10.09 #2715

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions lcci/10.09.Sorted Matrix Search/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,37 @@ public class Solution {
}
```

```swift
class Solution {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
for row in matrix {
if binarySearch(row, target) {
return true
}
}
return false
}

private func binarySearch(_ array: [Int], _ target: Int) -> Bool {
var left = 0
var right = array.count - 1

while left <= right {
let mid = left + (right - left) / 2
if array[mid] == target {
return true
} else if array[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}

return false
}
}
```

<!-- tabs:end -->

### 方法二:从左下角或右上角搜索
Expand Down
31 changes: 31 additions & 0 deletions lcci/10.09.Sorted Matrix Search/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,37 @@ public class Solution {
}
```

```swift
class Solution {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
for row in matrix {
if binarySearch(row, target) {
return true
}
}
return false
}

private func binarySearch(_ array: [Int], _ target: Int) -> Bool {
var left = 0
var right = array.count - 1

while left <= right {
let mid = left + (right - left) / 2
if array[mid] == target {
return true
} else if array[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}

return false
}
}
```

<!-- tabs:end -->

### Solution 2: Search from the Bottom Left or Top Right
Expand Down
28 changes: 28 additions & 0 deletions lcci/10.09.Sorted Matrix Search/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
for row in matrix {
if binarySearch(row, target) {
return true
}
}
return false
}

private func binarySearch(_ array: [Int], _ target: Int) -> Bool {
var left = 0
var right = array.count - 1

while left <= right {
let mid = left + (right - left) / 2
if array[mid] == target {
return true
} else if array[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}

return false
}
}