Skip to content

Commit

Permalink
Add solution for problem 4
Browse files Browse the repository at this point in the history
  • Loading branch information
0xff-dev committed Sep 21, 2023
1 parent 94e6099 commit 88a6421
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
34 changes: 34 additions & 0 deletions leetcode/1-100/0004.Median-of-Two-Sorted-Arrays/Solution.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,37 @@ func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {

return -1.0
}

func findMedianSortedArrays1(nums1 []int, nums2 []int) float64 {
l1 := len(nums1)
l2 := len(nums2)
targetIndex := (l1 + l2) / 2
index := 0
i, j := 0, 0
a, b := 0, 0
for i < l1 && j < l2 && index <= targetIndex {
index++
b = a
if nums1[i] < nums2[j] {
a = nums1[i]
i++
continue
}
a = nums2[j]
j++
}
for ; i < l1 && index <= targetIndex; i++ {
b = a
a = nums1[i]
index++
}
for ; j < l2 && index <= targetIndex; j++ {
b = a
a = nums2[j]
index++
}
if (l1+l2)&1 == 1 {
return float64(a)
}
return float64(a+b) / 2
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ func TestSolution(t *testing.T) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, ret, c.inputs)
}
ret = findMedianSortedArrays1(c.inputs[0], c.inputs[1])
if !reflect.DeepEqual(ret, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, ret, c.inputs)
}
})
}
}

0 comments on commit 88a6421

Please sign in to comment.