【leetcode慢速刷题记录】1. 两数之和
文章目录
- 前言
- 一、题目
- 二、方法
- 1.暴力破解
- 2.哈希表
- 其他一些总结
- (1)关于unordered_map
前言
经典面试题,其实比较简单,但鉴于刷题一遍容易忘,还是记录一下。
一、题目
二、方法
1.暴力破解
暴力破解可以解决很多问题,但是一般来说不太可能通过,因为耗时太长,但怎么说也是一种方法。
代码如下:
int* twoSum(int* nums, int numsSize, int target, int* returnSize){int* ret = NULL;for(int i=0; i<numsSize-1; i++){for(int j=i+1; j<numsSize; j++){if((nums[i]+nums[j])==target){ret = malloc(sizeof(int) * 2);ret[0]=i;ret[1]=j;*returnSize = 2;return (ret);}}}*returnSize = 0;return (returnSize);
}
2.哈希表
C语言实现代码如下:
struct hashTable {int key;int val;UT_hash_handle hh;
};struct hashTable* hashtable;struct hashTable* find(int ikey) {struct hashTable* tmp;HASH_FIND_INT(hashtable, &ikey, tmp);return tmp;
}void insert(int ikey, int ival) {struct hashTable* it = find(ikey);if (it == NULL) {struct hashTable* tmp = malloc(sizeof(struct hashTable));tmp->key = ikey, tmp->val = ival;HASH_ADD_INT(hashtable, key, tmp);} else {it->val = ival;}
}int* twoSum(int* nums, int numsSize, int target, int* returnSize) {hashtable = NULL;for (int i = 0; i < numsSize; i++) {struct hashTable* it = find(target - nums[i]);if (it != NULL) {int* ret = malloc(sizeof(int) * 2);ret[0] = it->val, ret[1] = i;*returnSize = 2;return ret;}insert(nums[i], i);}*returnSize = 0;return NULL;
}
C++语言代码实现如下:
class Solution {public:vector<int> twoSum(vector<int>& nums, int target) {unordered_map<int, int> hashtable;for (int i = 0; i < nums.size(); ++i) {auto it = hashtable.find(target - nums[i]);if (it != hashtable.end()) {return {it->second, i};}hashtable[nums[i]] = i;}return {};}
};
其他一些总结
(1)关于unordered_map
unordered_map记录元素的hash值,根据hash值判断元素是否相同。
- 效率:无论从查找、插入上来说,unordered_map的效率都优于hash_map,更优于map;
- 空间复杂度:hash_map最低,unordered_map次之,map最大。
unordered_map感觉速度和hash_map差不多,但是支持string做key,也可以使用复杂的对象作为key。
成员函数:
应用示例1:
1 // unordered_map::insert2 #include <iostream>3 #include <string>4 #include <unordered_map>5 using namespace std;6 7 void display(unordered_map<string,double> myrecipe,string str)8 {9 cout << str << endl;
10 for (auto& x: myrecipe)
11 cout << x.first << ": " << x.second << endl;
12 cout << endl;
13 }
14
15 int main ()
16 {17 unordered_map<string,double>
18 myrecipe,
19 mypantry = {{"milk",2.0},{"flour",1.5}};
20
21 /****************插入*****************/
22 pair<string,double> myshopping ("baking powder",0.3);
23 myrecipe.insert (myshopping); // 复制插入
24 myrecipe.insert (make_pair<string,double>("eggs",6.0)); // 移动插入
25 myrecipe.insert (mypantry.begin(), mypantry.end()); // 范围插入
26 myrecipe.insert ({{"sugar",0.8},{"salt",0.1}}); // 初始化数组插入(可以用二维一次插入多个元素,也可以用一维插入一个元素)
27 myrecipe["coffee"] = 10.0; //数组形式插入
28
29 display(myrecipe,"myrecipe contains:");
30
31 /****************查找*****************/
32 unordered_map<string,double>::const_iterator got = myrecipe.find ("coffee");
33
34 if ( got == myrecipe.end() )
35 cout << "not found";
36 else
37 cout << "found "<<got->first << " is " << got->second<<"\n\n";
38 /****************修改*****************/
39 myrecipe.at("coffee") = 9.0;
40 myrecipe["milk"] = 3.0;
41 display(myrecipe,"After modify myrecipe contains:");
42
43
44 /****************擦除*****************/
45 myrecipe.erase(myrecipe.begin()); //通过位置
46 myrecipe.erase("milk"); //通过key
47 display(myrecipe,"After erase myrecipe contains:");
48
49 /****************交换*****************/
50 myrecipe.swap(mypantry);
51 display(myrecipe,"After swap with mypantry, myrecipe contains:");
52
53 /****************清空*****************/
54 myrecipe.clear();
55 display(myrecipe,"After clear, myrecipe contains:");
56 return 0;
57 }
58 /*
59 myrecipe contains:
60 salt: 0.1
61 milk: 2
62 flour: 1.5
63 coffee: 10
64 eggs: 6
65 sugar: 0.8
66 baking powder: 0.3
67
68 found coffee is 10
69
70 After modify myrecipe contains:
71 salt: 0.1
72 milk: 3
73 flour: 1.5
74 coffee: 9
75 eggs: 6
76 sugar: 0.8
77 baking powder: 0.3
78
79 After erase myrecipe contains:
80 flour: 1.5
81 coffee: 9
82 eggs: 6
83 sugar: 0.8
84 baking powder: 0.3
85
86 After swap with mypantry, myrecipe contains:
87 flour: 1.5
88 milk: 2
89
90 After clear, myrecipe contains:
91 */
应用示例2:(遍历)
1 // unordered_map::bucket_count2 #include <iostream>3 #include <string>4 #include <unordered_map>5 using namespace std;6 7 int main ()8 {9 unordered_map<string,string> mymap =
10 {11 {"house","maison"},
12 {"apple","pomme"},
13 {"tree","arbre"},
14 {"book","livre"},
15 {"door","porte"},
16 {"grapefruit","pamplemousse"}
17 };
18 /************begin和end迭代器***************/
19 cout << "mymap contains:";
20 for ( auto it = mymap.begin(); it != mymap.end(); ++it )
21 cout << " " << it->first << ":" << it->second;
22 cout << endl;
23 /************bucket操作***************/
24 unsigned n = mymap.bucket_count();
25
26 cout << "mymap has " << n << " buckets.\n";
27
28 for (unsigned i=0; i<n; ++i)
29 {30 cout << "bucket #" << i << "'s size:"<<mymap.bucket_size(i)<<" contains: ";
31 for (auto it = mymap.begin(i); it!=mymap.end(i); ++it)
32 cout << "[" << it->first << ":" << it->second << "] ";
33 cout << "\n";
34 }
35
36 cout <<"\nkey:'apple' is in bucket #" << mymap.bucket("apple") <<endl;
37 cout <<"\nkey:'computer' is in bucket #" << mymap.bucket("computer") <<endl;
38
39 return 0;
40 }
41 /*
42 mymap contains: door:porte grapefruit:pamplemousse tree:arbre apple:pomme book:livre house:maison
43 mymap has 7 buckets.
44 bucket #0's size:2 contains: [book:livre] [house:maison]
45 bucket #1's size:0 contains:
46 bucket #2's size:0 contains:
47 bucket #3's size:2 contains: [grapefruit:pamplemousse] [tree:arbre]
48 bucket #4's size:0 contains:
49 bucket #5's size:1 contains: [apple:pomme]
50 bucket #6's size:1 contains: [door:porte]
51
52 key:'apple' is in bucket #5
53
54 key:'computer' is in bucket #6
55 */
(以上内容来自:详细介绍C++STL:unordered_map)
【leetcode慢速刷题记录】1. 两数之和相关推荐
- 【leedcode刷题1】两数之和
[leedcode刷题 1]两数之和 大家好,小生不才,从今天开始将自己刷题的过程记录在博客中,因为能力有限,所以如果有什么错的地方希望大家积极指正,不胜感激. 题目 给定一个整数数组 nums 和一 ...
- leetcode刷题:2.两数之和
本篇博客介绍如何找到两数之和.获取相加的两个数获取最终target的方法. 先看如下图: 我们很容易想到暴力解法.即两次循环获取结果,第一次循环循环黑圈,我们先假定第一个黑圈中1,是我们要的数,然后接 ...
- LeetCode刷题笔记——001两数之和
题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能使用 ...
- 【leetcode】力扣刷题(1):两数之和(Go、Python)
一.问题描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个 ...
- 【菜菜子力扣刷题】1.两数之和
题目描述 我的代码 /*** Note: The returned array must be malloced, assume caller calls free().*/ int* twoSum( ...
- LeetCode刷题笔记- 15.三数之和
LeetCode刷题笔记- 15.三数之和 C语言 题目 注意点 C语言 /*** Return an array of arrays of size *returnSize.* The sizes ...
- 【leetcode刷题】21.三数之和——Java版
⭐欢迎订阅<leetcode>专栏,每日一题,每天进步⭐ 一题二写,三数之和,题解四瞅五瞄六瞧,水平还七上八下九流,十分辣鸡. --leetcode此题热评 前言 哈喽,大家好,我是一条. ...
- 力扣刷题-单链表两数相加
分区:链表 2.两数相加 题目描述: 给你两个 非空 的链表,表示两个非负的整数.它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字. 请你将两个数相加,并以相同形式返回一个表 ...
- LeetCode(C++)刷题计划:15-三数之和
15-三数之和 @Author:CSU张扬 @Email:csuzhangyang@gmail.com or csuzhangyang@qq.com Category Difficulty Pass ...
最新文章
- CentOS6.3安装MySQL5.5
- 博士申请 | 澳大利亚悉尼科技大学招收人工智能/软件工程方向全奖博士生
- python论坛签到_论坛自动签到教程
- JsonUtils.java
- REVERSE-PRACTICE-BUUCTF-13
- linux相关命令介绍
- ubuntu下安装Node.js(源码安装)
- 【caffe】ubuntu配置matlab接口----matcaffe
- dockerfile制作docker镜像
- 推荐:网站SEO内链详细操作指南
- php composer 无法下载,composer给laravel下载扩展包 无法下载的问题
- cocos2dx[3.x](11)——拖尾渐隐效果MotionStreak
- 获取mac电脑最高权限
- 14_单引号和双引号
- 建数据库表需要注意哪些点
- python3中利用serial模块实现单片机与python上位机的通信(串口调试助手)
- 什么是构造方法,为什么要使用构造方法
- 华为笔记本linux usb启动,华为MateBook D(2018) BIOS设置u盘启动教程
- Matlab中feedback函数的用法
- deficit记忆_一个多动症儿童是如何成为记忆天才的?!
热门文章
- SAP ABAP性能优化 - 调优工具 SM50 | ST05 | SAT
- Java根据子节点获取最上层节点(根节点)数据和所有上级集合
- 阿里巴巴内推一面过程
- IDEA插件系列(56):CamelCase插件——驼峰转换
- 刨根问底 Kafka,面试过程真好使
- 在Docker中使用Python Selenium和Headless Chrome进行网站自动化测试的方法
- 从光驱型号获得光驱详细配置参数信息
- 2020-第三届江西省高校网络安全技能大赛
- SQL Server 2005 术语词汇表
- 【机器学习】监督学习,非监督学习,半监督学习三者的定义区别及举例分析