hello-algo/codes/swift/chapter_searching/linear_search.swift
nuomi1 1665fe176c
feat: add Swift codes for chapter_searching articles (#309)
* feat: add Swift codes for linear_search article

* feat: add Swift codes for binary_search article

* feat: add Swift codes for hashing_search article
2023-01-30 15:43:29 +08:00

53 lines
1.3 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* File: linear_search.swift
* Created Time: 2023-01-28
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* 线 */
func linearSearch(nums: [Int], target: Int) -> Int {
//
for i in nums.indices {
//
if nums[i] == target {
return i
}
}
// -1
return -1
}
/* 线 */
func linearSearch(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 = linearSearch(nums: nums, target: target)
print("目标元素 3 的索引 = \(index)")
/* 线 */
let head = ListNode.arrToLinkedList(arr: nums)
let node = linearSearch(head: head, target: target)
print("目标结点值 3 的对应结点对象为 \(node!)")
}
}