Skip to content

Commit

Permalink
Merge pull request #183 from soapyigu/Search
Browse files Browse the repository at this point in the history
[Search] Add solutions to Search 2D Matrix I and II
  • Loading branch information
soapyigu authored Dec 26, 2016
2 parents 5ef7a59 + b45e086 commit 8e41c9c
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
51 changes: 51 additions & 0 deletions Search/Search2DMatrix.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* Question Link: https://leetcode.com/problems/search-a-2d-matrix/
* Primary idea: Search col and then binary search row
*
* Time Complexity: O(log(m + n), Space Complexity: O(1)
*/

class Search2DMatrix {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
if matrix.count == 0 || matrix[0].count == 0 {
return false
}

let rowNum = searchRow(matrix, target)
return searchCol(matrix[rowNum], target)
}

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

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

return matrix[right][0] <= target ? right : left
}

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

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

return false
}
}
28 changes: 28 additions & 0 deletions Search/Search2DMatrixII.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Question Link: https://leetcode.com/problems/search-a-2d-matrix-ii/
* Primary idea: Start from last element at first row, then move downwards or backwards
*
* Time Complexity: O(m + n), Space Complexity: O(1)
*/

class Search2DMatrixII {
func searchMatrix(_ matrix: [[Int]], _ target: Int) -> Bool {
guard matrix.count > 0 else {
return false
}

var row = 0, col = matrix[0].count - 1

while row < matrix.count && col >= 0 {
if matrix[row][col] == target {
return true
} else if matrix[row][col] < target {
row += 1
} else {
col -= 1
}
}

return false
}
}

0 comments on commit 8e41c9c

Please sign in to comment.