hello-algo/codes/swift/chapter_searching/hashing_search.swift

51 lines
1.5 KiB
Swift
Raw Normal View History

/**
* File: hashing_search.swift
* Created Time: 2023-01-28
* Author: nuomi1 (nuomi1@qq.com)
*/
import utils
/* */
func hashingSearchArray(map: [Int: Int], target: Int) -> Int {
// key: value:
// key -1
return map[target, default: -1]
}
/* */
func hashingSearchLinkedList(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 = hashingSearchArray(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 = hashingSearchLinkedList(map: map1, target: target)
print("目标结点值 3 的对应结点对象为 \(node!)")
}
}