Skip to content

Commit

Permalink
✨ Problem 004 Two Pointer Solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jobearrr committed Jul 20, 2024
1 parent c418bf7 commit 81775ee
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//
// MedianOfTwoSortedArraysTwoPointerSolution.swift
// LeetSwift
//
// Created by Jobert Sá on 20/07/2024.
//

import Core
import Foundation
import Problems

final class MedianOfTwoSortedArraysTwoPointerSolution: MedianOfTwoSortedArraysDefinition {

func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
let total = nums1.count + nums2.count
let mid = total / 2
var i = 0, j = 0
var current = 0, previous = 0

for _ in 0...mid {
previous = current
if i < nums1.count && (j >= nums2.count || nums1[i] < nums2[j]) {
current = nums1[i]
i += 1
} else {
current = nums2[j]
j += 1
}
}

if total % 2 == 0 {
return Double(current + previous) / 2.0
} else {
return Double(current)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//
// MedianOfTwoSortedArraysTwoPointerSolutionTests.swift
// LeetSwift
//
// Created by Jobert Sá on 20/07/2024.
//

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

final class MedianOfTwoSortedArraysTwoPointerSolutionTests: XCTestCase {

let solution: MedianOfTwoSortedArraysDefinition = MedianOfTwoSortedArraysTwoPointerSolution()

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

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

XCTAssertEqual(output, testData.expectedOutput)
}
}
}

extension MedianOfTwoSortedArraysTwoPointerSolutionTests: MedianOfTwoSortedArraysTestCaseProvider { }

0 comments on commit 81775ee

Please sign in to comment.