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/codes/swift/chapter_searching/hashing_search.swift

51 lines
1.5 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: 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!)")
}
}