题目地址
https://leetcode.com/problems/intersection-of-two-arrays/description/
题目描述
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Note:
Each element in the result must be unique.
The result can be in any order.
思路
先遍历第一个数组,将其存到hashtable中,
然后遍历第二个数组,如果在hashtable中存在就push到return,然后清空hashtable即可。
关键点解析
无
代码
- 语言支持:JS, Python
Javascript Code:
/* * @lc app=leetcode id=349 lang=javascript * * [349] Intersection of Two Arrays * * https://leetcode.com/problems/intersection-of-two-arrays/description/ * * algorithms * Easy (53.11%) * Total Accepted: 203.6K * Total Submissions: 380.9K * Testcase Example: '[1,2,2,1]\n[2,2]' * * Given two arrays, write a function to compute their intersection. * * Example 1: * * * Input: nums1 = [1,2,2,1], nums2 = [2,2] * Output: [2] * * * * Example 2: * * * Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] * Output: [9,4] * * * Note: * * * Each element in the result must be unique. * The result can be in any order. * * * * */ /** * @param {number[]} nums1 * @param {number[]} nums2 * @return {number[]} */ var intersection = function(nums1, nums2) { const visited = {}; const ret = []; for(let i = 0; i < nums1.length; i++) { const num = nums1[i]; visited[num] = num; } for(let i = 0; i < nums2.length; i++) { const num = nums2[i]; if (visited[num] !== undefined) { ret.push(num); visited[num] = undefined; } } return ret; };
Python Code:
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: visited, result = {}, [] for num in nums1: visited[num] = num for num in nums2: if num in visited: result.append(num) visited.pop(num) return result # 另一种解法:利用 Python 中的集合进行计算 def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return set(nums1) & set(nums2)LeetCode题解1879. Two Sum VII
给定一个已经 按绝对值升序排列 的数组,找到两个数使他们加起来的和等于特定数。函数应该返回这两个数的下标,index1必须小于index2。注意返回的值是0-based。请使用双指针完成本题,否则你有可能会被取消比赛资格。注意事项:```- 数据保证nums中的所有数的互不相同的。- nums数组长度≤100000- nums内的数≤1000000000``…
LeetCode题解342.power-of-four题目地址 https://leetcode.com/problems/power-of-four/description/ 题目描述 Given an integer (signed 32 bits), write a function to check whether it is a power of 4. Example 1: Input: 16 Out…
LeetCode题解200.number-of-islands题目地址 https://leetcode.com/problems/number-of-islands/description/ 题目描述 Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by …
LeetCode题解1020.number-of-enclaves题目地址 https://leetcode-cn.com/problems/number-of-enclaves/ 题目描述 给出一个二维数组 A,每个单元格为 0(代表海)或 1(代表陆地)。 移动是指在陆地上从一个地方走到另一个地方(朝四个方向之一)或离开网格的边界。 返回网格中无法在任意次数的移动中离开网格边界的陆地单元格的数量。 示例 1: 输入…
LeetCode题解1297.maximum-number-of-occurrences-of-a-substring题目地址(1297. 子串的最大出现次数) https://leetcode-cn.com/problems/maximum-number-of-occurrences-of-a-substring 题目描述 给你一个字符串 s ,请你返回满足以下条件且出现次数最大的 任意 子串的出现次数: 子串中不同字母的数目必须小于等于 maxLetters 。 子串的…