You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/zh-hant/codes/swift/chapter_searching/linear_search.swift

54 lines
1.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* File: linear_search.swift
* Created Time: 2023-01-28
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
func linearSearchArray(nums: [Int], target: Int) -> Int {
//
for i in nums.indices {
//
if nums[i] == target {
return i
}
}
// -1
return -1
}
/* */
func linearSearchLinkedList(head: ListNode?, target: Int) -> ListNode? {
var head = head
//
while head != nil {
//
if head?.val == target {
return head
}
head = head?.next
}
// null
return nil
}
@main
enum LinearSearch {
/* Driver Code */
static func main() {
let target = 3
/* */
let nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
let index = linearSearchArray(nums: nums, target: target)
print("目標元素 3 的索引 = \(index)")
/* */
let head = ListNode.arrToLinkedList(arr: nums)
let node = linearSearchLinkedList(head: head, target: target)
print("目標節點值 3 的對應節點物件為 \(node!)")
}
}