Skip to content

Commit

Permalink
✨ Problem 004 Binary Search Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jobearrr committed Jul 20, 2024
1 parent 6cdf35d commit 6ca6cbe
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//
// MedianOfTwoSortedArraysBinarySearchSolution.swift
// LeetSwift
//
// Created by Jobert Sá on 20/07/2024.
//

import Core
import Foundation
import Problems

final class MedianOfTwoSortedArraysBinarySearchSolution: MedianOfTwoSortedArraysDefinition {

func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
let a = nums1.count < nums2.count ? nums1 : nums2
let b = nums1.count < nums2.count ? nums2 : nums1
let m = a.count
let n = b.count

var low = 0
var high = m

while low <= high {
let i = (low + high) / 2
let j = (m + n + 1) / 2 - i

let maxLeftA = (i == 0) ? Int.min : a[i - 1]
let minRightA = (i == m) ? Int.max : a[i]

let maxLeftB = (j == 0) ? Int.min : b[j - 1]
let minRightB = (j == n) ? Int.max : b[j]

if maxLeftA <= minRightB && maxLeftB <= minRightA {
if (m + n) % 2 == 0 {
return Double(max(maxLeftA, maxLeftB) + min(minRightA, minRightB)) / 2.0
} else {
return Double(max(maxLeftA, maxLeftB))
}
} else if maxLeftA > minRightB {
high = i - 1
} else {
low = i + 1
}
}

return 0.0 // Invalid input case
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// MedianOfTwoSortedArraysBinarySearchSolutionTests.swift
// LeetSwift
//
// Created by Jobert Sá on 20/07/2024.
//

import XCTest
@testable import Problems
@testable import Solutions
@testable import TestSupport

final class MedianOfTwoSortedArraysBinarySearchSolutionTests: XCTestCase {

let solution: MedianOfTwoSortedArraysDefinition = MedianOfTwoSortedArraysBinarySearchSolution()

func testSolution() {
for testData in data {
let input = testData.input

let output = solution.findMedianSortedArrays(input.nums1, input.nums2)

XCTAssertEqual(output, testData.expectedOutput)
}
}
}

extension MedianOfTwoSortedArraysBinarySearchSolutionTests: MedianOfTwoSortedArraysTestCaseProvider { }

0 comments on commit 6ca6cbe

Please sign in to comment.