-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
...lutions/004 - Median of Two Sorted Arrays/MedianOfTwoSortedArraysTwoPointerSolution.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |
28 changes: 28 additions & 0 deletions
28
...ts/004 - Median of Two Sorted Arrays/MedianOfTwoSortedArraysTwoPointerSolutionTests.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { } |