110 lines
2.5 KiB
Text
110 lines
2.5 KiB
Text
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "674f782d-c014-4749-ba16-5f107f8c31d9",
|
|
"metadata": {
|
|
"tags": []
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import qualified Data.IntMap.Strict as Map"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 6,
|
|
"id": "6dd70e30-9203-45a8-957b-a0a8459a3a28",
|
|
"metadata": {
|
|
"tags": []
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"enumerate = zip [0..]\n",
|
|
"\n",
|
|
"twoSum' :: Map.IntMap Int -> [(Int, Int)] -> Int -> [Int]\n",
|
|
"twoSum' hm [] target = []\n",
|
|
"twoSum' hm ((i, n):xs) target =\n",
|
|
" let remainder = target - n in\n",
|
|
" let index = Map.lookup remainder hm in\n",
|
|
" case index of\n",
|
|
" Nothing -> twoSum' (Map.insert n i hm) xs target\n",
|
|
" Just k -> [k, i]\n",
|
|
"\n",
|
|
"twoSum :: [Int] -> Int -> [Int]\n",
|
|
"twoSum nums target =\n",
|
|
" let hm = Map.empty in\n",
|
|
" let nums' = enumerate nums in\n",
|
|
" twoSum' hm nums' target"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 7,
|
|
"id": "0fd587ec-b060-4722-9bbd-d4f6dd83efe2",
|
|
"metadata": {
|
|
"tags": []
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"-- Open Assistant:\n",
|
|
"-- Define a custom function to check assertions.\n",
|
|
"assert :: Bool -> String -> IO ()\n",
|
|
"assert True msg = pure ()\n",
|
|
"assert False msg = ioError $ userError msg"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "85cd567a-8124-4a77-8108-0183a9e6b471",
|
|
"metadata": {
|
|
"tags": []
|
|
},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"\"All Done\""
|
|
]
|
|
},
|
|
"metadata": {},
|
|
"output_type": "display_data"
|
|
}
|
|
],
|
|
"source": [
|
|
"assert (twoSum [3,3] 6 == [0,1]) \"Case 1 Failed\"\n",
|
|
"assert (twoSum [3,2,4] 6 == [1,2]) \"Case 2 Failed\"\n",
|
|
"assert (twoSum [2,7,11,15] 9 == [0,1]) \"Case 3 Failed\"\n",
|
|
"\n",
|
|
"print \"All Done\""
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "c631b602-1a58-478b-8a73-294f2e34176d",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "haskell-Haskell kernel",
|
|
"language": "haskell",
|
|
"name": "haskell-haskell"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": "Haskell",
|
|
"file_extension": ".hs",
|
|
"mimetype": "text/x-haskell",
|
|
"name": "haskell",
|
|
"pygments_lexer": "Haskell",
|
|
"version": "9.0.2"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|