hello-algo/codes/swift/chapter_searching/hashing_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

50 lines
1.5 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: hashing_search.swift
* Created Time: 2023-01-28
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
func hashingSearch(map: [Int: Int], target: Int) -> Int {
// key: value:
// key -1
return map[target, default: -1]
}
/* */
func hashingSearch1(map: [Int: ListNode], target: Int) -> ListNode? {
// key: value:
// key null
return map[target]
}
@main
enum HashingSearch {
/* Driver Code */
static func main() {
let target = 3
/* */
let nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
//
var map: [Int: Int] = [:]
for i in nums.indices {
map[nums[i]] = i // key: value:
}
let index = hashingSearch(map: map, target: target)
print("目标元素 3 的索引 = \(index)")
/* */
var head = ListNode.arrToLinkedList(arr: nums)
//
var map1: [Int: ListNode] = [:]
while head != nil {
map1[head!.val] = head! // key: value:
head = head?.next
}
let node = hashingSearch1(map: map1, target: target)
print("目标结点值 3 的对应结点对象为 \(node!)")
}
}