350. Intersection of Two Arrays II -- 双指针、哈希表、排序、二分搜索
来源:互联网 发布:python 毫秒级时间戳 编辑:程序博客网 时间:2024/05/21 10:21
350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]
解1:双指针,并把结果添加到栈中。
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ nums1.sort() nums2.sort() p1 = 0 p2 = 0 ans = [] while (p1 < len(nums1)) and (p2 < len(nums2)): if nums1[p1] == nums2[p2]: ans.append(nums1[p1]) p1 += 1 p2 += 1 elif nums1[p1] < nums2[p2]: p1 += 1 else: p2 += 1 return ans
解2:
哈希表,首先把nums1的字符添加到哈希表中,然后遍历nums2,找到一个nums1中有的数并且计数大于0,就添加到放回的列表中,并且计数减去1.
class Solution(object): def intersect(self, nums1, nums2): """ :type nums1: List[int] :type nums2: List[int] :rtype: List[int] """ ans = [] d = {} for num in nums1: d[num] = d[num] + 1 if num in d else 1 for j in nums2: if j in d and d[j] > 0: ans.append(j) d[j] -= 1 return ans
阅读全文
0 0
- 350. Intersection of Two Arrays II -- 双指针、哈希表、排序、二分搜索
- leetcode 350---Intersection of Two Arrays II 数组 双指针 排序
- 350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II【E】
- 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- 2
- 设计模式之适配器模式
- 在Word文档里启用限制编辑
- LeetCode:Maximum Subarray
- 【codeforces 808】B.Average Sleep Time
- 350. Intersection of Two Arrays II -- 双指针、哈希表、排序、二分搜索
- 从0~n-1中随机k个有序元素
- 项目沟通管理脉络
- 单链表
- uboot、linux内核打补丁及根文件系统生成
- 各种国内本地源设置
- Pandas模块1
- MFC初学之音乐播放器1_2续
- js中的this问题总结