Swift 每週五題 LeetCode(5)

LULU
6 min readFeb 23, 2022

--

這週遇到的題目剛好比較輕鬆一點XD難得三天就寫了五題ya

26. Remove Duplicates from Sorted Array (Easy)

這題用了兩種解法

func removeDuplicates(_ nums: inout [Int]) -> Int {
// 方法一:直接用函式取出重複後排序
// nums = Array(Set(nums)).sorted()
// return nums.count
//方法二:找到相同的就刪除
var index = nums.count - 1
while index > 0 {
if nums[index - 1] == nums[index] {
nums.remove(at: index)
}
index -= 1
}
return nums.count
}

28. Implement strStr() (Easy)

func strStr(_ haystack: String, _ needle: String) -> Int {
if needle.isEmpty {
return 0
} //使用切割字串函式 放參考連結在下方
let arr = haystack.components(separatedBy: needle)
if arr.first!.count == haystack.count {
return -1
}
return arr.first!.count
}

29. Divide Two Integers (Medium)

想偷偷抱怨一下這是一題垃圾題!!我明明就選 Top Interview沒想到竟然有不少公司挑這種鄙視工程師智商的題目(凸
寫完不解釋😤相信大家都能理解的

func divide(_ dividend: Int, _ divisor: Int) -> Int {
var ans = dividend / divisor
if ans > INT32_MAX {
return Int(INT32_MAX)
}
return ans
}

33. Search in Rotated Sorted Array (Medium)

這題跟下一題很類似,偷懶的方法跟正規的二分法都可以解,下一題會用二分法來解題

func search(_ nums: [Int], _ target: Int) -> Int {
var i = 0

while i < nums.count {
if nums[i] == target {
return i
}
i += 1
}
return -1
}

34. Find First and Last Position of Element in Sorted Array (Medium)

func searchRange(_ nums: [Int], _ target: Int) -> [Int] {
var star = -1
var end = -1 //預設值

var left = 0
var right = nums.count - 1

while left <= right {
let mid = (left + right) / 2
// find first
// not found
if star == -1 {
if nums[mid] == target {
// only 1 element ex:[1] mid = (0 + 0) / 2 = 0, found first || found target(mid) > previous number
if mid == 0 || nums[mid] > nums[mid - 1] {
star = mid
left = 0
right = nums.count - 1
} else {
right = mid - 1
}
continue
}
// find last
}else if end == -1 { //looking for last
if nums[mid] == target { // found last
if mid == right || nums[mid] < nums[mid + 1] {
end = mid
return [star, end]
} else {
left = mid + 1
}
continue
}
} // if not found yet, keep looking
if nums[mid] <= target {
left = mid + 1
} else {
right = mid - 1
}
}
return[star, end]
}

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

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

--

--

LULU
LULU

Written by LULU

Hi👋 I’m iOS developer, I hope I can grow with you guys ☺️ Let’s learn more together.

Responses (1)

Write a response