diff --git a/Sources/Solutions/004 - Median of Two Sorted Arrays/MedianOfTwoSortedArraysTwoPointerSolution.swift b/Sources/Solutions/004 - Median of Two Sorted Arrays/MedianOfTwoSortedArraysTwoPointerSolution.swift new file mode 100644 index 0000000..82d7cef --- /dev/null +++ b/Sources/Solutions/004 - Median of Two Sorted Arrays/MedianOfTwoSortedArraysTwoPointerSolution.swift @@ -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) + } + } +} diff --git a/Tests/SolutionsTests/004 - Median of Two Sorted Arrays/MedianOfTwoSortedArraysTwoPointerSolutionTests.swift b/Tests/SolutionsTests/004 - Median of Two Sorted Arrays/MedianOfTwoSortedArraysTwoPointerSolutionTests.swift new file mode 100644 index 0000000..d4623f5 --- /dev/null +++ b/Tests/SolutionsTests/004 - Median of Two Sorted Arrays/MedianOfTwoSortedArraysTwoPointerSolutionTests.swift @@ -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 { }