張又壬
1 min readApr 13, 2022

--

跟你分享一下,最近也開始解 LeetCode 解到第四題,想好久,有想過兩個 array 加起來後直接 sort 暴力破解,但覺得答案這樣會不會太簡單了,就另外又想了一個,就是兩個 array 加起來後,如果排序好了,我只要取得 array 中間一個或兩個值就OK了啊,意思就是我其實只要把新的 array 排到一半就可以拿到答案了啊!

func mergeArray(_ nums1: [Int], _ nums2: [Int]) -> Double {

let count = nums1.count + nums2.count

var condition = 0

let isOdd = (count % 2) == 1

if isOdd {

condition = Int(ceil(Double(count) / 2.0))

} else {

condition = count / 2 + 1

}

var index1 = 0, index2 = 0, arrayCount = 0, sum = 0

while arrayCount < condition {

var temp = 0

if index1 < nums1.count && index2 < nums2.count {

if nums1[index1] <= nums2[index2] {

temp = nums1[index1]

index1 += 1

} else {

temp = nums2[index2]

index2 += 1

}

} else if index1 < nums1.count {

temp = nums1[index1]

index1 += 1

} else if index2 < nums2.count {

temp = nums2[index2]

index2 += 1

}

arrayCount += 1

if isOdd {

if arrayCount == condition {

sum = temp

}

} else {

if arrayCount == condition - 1 || arrayCount == condition {

sum += temp

}

}

}

return isOdd ? Double(sum) : Double(sum) / 2

}

大概就是這樣這個 function 是解兩個 array 都有值的情況,剩下只有單一 array 的情況比較簡單就不貼了

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

張又壬
張又壬

Written by 張又壬

目前正在努力學習 swift

No responses yet

Write a response