Leetcode每日一道 -- 两数之和
2018-11-21 23:52
288 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_19332527/article/details/84332061
题目链接: https://leetcode-cn.com/problems/two-sum/description/
题目描述:
[code]给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的 两个 整数。 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。 示例: 给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
题目分析 : 最直观想法是暴力搜索,复杂度是O(N^2),但是这样是不过的。还有一种方式是排序之后,利用双指针方法进行搜索,复杂度是O(n*lgn),依然很复杂。比较理想的想法是看到一个数字能够快速找到 target-nums[i] 是否在数组中,本质上是一个检索问题,最快的查找方式就是利用Hash映射查找。Python中的set是基于Hash映射进行查找的,在C++中unorder_map是基于Hash映射进行查找的。代码如下:
[code]class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ nums_set=set(nums) #将nums转为集合 for i in range(0,len(nums)): if (target-nums[i]) in nums_set: #判断是否nums[i]的补数在集合中 low=i for j in range(i+1,len(nums)): #上面判断出了nums[i]的补数在集合中,需要查找下标 if nums[j]+nums[i]==target: return [i,j]
C++代码如下: 声明C++我没有和python一样用 集合 进行查找是因为c++的set是基于红黑树的查找方式,查找的效率是O(logn)
[code]class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int,int> d; int len=nums.size(); vector<int> res; for(int i=0;i<len;i++) { if(d.count(target-nums[i])) //判断target-nums[i]是否在d的key值列表中 { res.push_back(d[target-nums[i]]); res.push_back(i); return res; } else { d[nums[i]]=i; } } } };
知识点总结:
(1). Python 的set类型和C++的unordered_map是由Hash映射实现的,查找效率是O(n)。 C++的map和set是基于红黑树的,查找速度是O(logn)。
(2).记住一个API:
ordered_map<int,int> d: //声明一个无序映射
d[i]=j; //对i 键值赋值
d.count(i)!=0 d.find(i) != d.end() //在d的键值中查找i是否存在
阅读更多相关文章推荐
- Leetcode每日一道 -- 两数相加
- (LeetCode每日一刷01)两数之和
- Leetcode 每日一道
- Leetcode每日一道 -- 整数反转
- Leetcode每日一道 -- 无重复字符的最长子串
- 【一天一道LeetCode】#225. Implement Stack using Queues
- LeetCode-Two Sum(两数之和)
- 【一天一道LeetCode】#44. Wildcard Matching
- 每日一恋 - LeetCode 328. Odd Even Linked List(奇偶链表)
- 【一天一道LeetCode】#5 Longest Palindromic Substring
- 【一天一道LeetCode】#47. Permutations II
- 【一天一道LeetCode】#104. Maximum Depth of Binary Tree
- [LeetCode] 170. Two Sum III - Data structure design 两数之和之三 - 数据结构设计
- 【一天一道LeetCode】#105. Construct Binary Tree from Preorder and Inorder Traversal
- [leetcode]两数相加
- 【一天一道LeetCode】#107. Binary Tree Level Order Traversal II
- 每日一道算法题——3个数字相加等于0
- 【一天一道LeetCode】#8. String to Integer (atoi)
- 【一天一道LeetCode】#111. Minimum Depth of Binary Tree
- 每日一道算法题:奇偶排序