116 lines
2.5 KiB
Text
116 lines
2.5 KiB
Text
|
{
|
||
|
"cells": [
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"id": "92b94045-a058-4b99-bfb6-7709a2a96f1a",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# First variant O(n^2)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": null,
|
||
|
"id": "764a6c5e-5fa8-41be-9ec2-2b097ed29af6",
|
||
|
"metadata": {
|
||
|
"tags": []
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {\n",
|
||
|
" for (i, n) in nums.iter().enumerate() {\n",
|
||
|
" for (k, m) in nums.iter().enumerate() {\n",
|
||
|
" if i == k {\n",
|
||
|
" continue;\n",
|
||
|
" } else if n + m == target {\n",
|
||
|
" return vec![i as i32, k as i32];\n",
|
||
|
" }\n",
|
||
|
" }\n",
|
||
|
" }\n",
|
||
|
" vec![]\n",
|
||
|
"}"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"id": "4278ee69-8a33-480c-a33b-1049bcec1eed",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Second variant O(n)"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 24,
|
||
|
"id": "7ad2762a-1deb-46ce-93fb-84b6ef637951",
|
||
|
"metadata": {
|
||
|
"tags": []
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"use std::collections::HashMap;\n",
|
||
|
"\n",
|
||
|
"pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {\n",
|
||
|
" let mut hm = HashMap::<i32, i32>::new();\n",
|
||
|
" \n",
|
||
|
" for (i, n) in nums.into_iter().enumerate() {\n",
|
||
|
" if let Some(k) = hm.get(&(target - n)) {\n",
|
||
|
" return vec![*k, i as i32];\n",
|
||
|
" } else {\n",
|
||
|
" hm.insert(n, i as i32);\n",
|
||
|
" }\n",
|
||
|
" }\n",
|
||
|
" vec![]\n",
|
||
|
"}"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "markdown",
|
||
|
"id": "d14e0757-f7eb-4c52-aab7-53a47b707377",
|
||
|
"metadata": {},
|
||
|
"source": [
|
||
|
"# Tests"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": 25,
|
||
|
"id": "8bdf4378-b7b4-4edb-a409-4e3f98517c41",
|
||
|
"metadata": {
|
||
|
"tags": []
|
||
|
},
|
||
|
"outputs": [],
|
||
|
"source": [
|
||
|
"assert_eq!(two_sum(vec![2,7,11,15], 9), vec![0,1]);\n",
|
||
|
"assert_eq!(two_sum(vec![3,2,4], 6), vec![1,2]);\n",
|
||
|
"assert_eq!(two_sum(vec![3,3], 6), vec![0,1]);"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
"cell_type": "code",
|
||
|
"execution_count": null,
|
||
|
"id": "150230c1-b43b-4275-8be7-3f35761cb19f",
|
||
|
"metadata": {},
|
||
|
"outputs": [],
|
||
|
"source": []
|
||
|
}
|
||
|
],
|
||
|
"metadata": {
|
||
|
"kernelspec": {
|
||
|
"display_name": "rust-Rust kernel",
|
||
|
"language": "rust",
|
||
|
"name": "rust-rust"
|
||
|
},
|
||
|
"language_info": {
|
||
|
"codemirror_mode": "rust",
|
||
|
"file_extension": ".rs",
|
||
|
"mimetype": "text/rust",
|
||
|
"name": "Rust",
|
||
|
"pygment_lexer": "rust",
|
||
|
"version": ""
|
||
|
}
|
||
|
},
|
||
|
"nbformat": 4,
|
||
|
"nbformat_minor": 5
|
||
|
}
|