Files
hello-algo/ja/codes/swift/chapter_searching/linear_search.swift
Yudong Jin d7b2277d2b Re-translate the Japanese version (#1871)
* Retranslate Japanese docs with GPT-5.4

* Retranslate Japanese code with GPT-5.4
2026-03-30 07:30:15 +08:00

54 lines
1.5 KiB
Swift
Raw Permalink 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 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!)")
}
}