LeetCode 349. Intersection of Two Arrays
来源:互联网 发布:品类管理数据分析 编辑:程序博客网 时间:2024/06/07 09:03
349. Intersection of Two Arrays
Description
Given two arrays, write a function to compute their intersection.
Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].Note:1.Each element in the result must be unique.2.The result can be in any order.
Solution
- 题意即求两个数组的交集
- 我的做法并不好,如果数据范围太大就会造成溢出。
- 我的做法是用两个桶,将每个数组对应的数用0-1表示,比如nums1中有个数是6,那么num1(桶)下标为6的位置用1填充,最后两个同做与运算,从而得到交集,代码如下
int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) { int *rnt = (int *)malloc(sizeof(int) * (nums1Size > nums2Size ? nums1Size : nums2Size)); memset(rnt,0,sizeof(rnt)); if (nums1Size == 0 || nums2Size == 0) return rnt; int num1[100010]; int num2[100010]; memset(num1,0,sizeof(num1)); memset(num2,0,sizeof(num2)); int max1 = nums1[0],max2 = nums2[0]; for (int i = 0;i < nums1Size;i++) { if (nums1[i] > max1) max1 = nums1[i]; num1[nums1[i]] = 1; } for (int i = 0;i < nums2Size;i++) { if (nums2[i] > max2) max2 = nums2[i]; num2[nums2[i]] = 1; } int MAX = max1 > max2 ? max1 : max2; int count = 0; for (int i = 0;i <= MAX;i++) { if (num1[i] && num2[i]) { rnt[count++] = i; } } *returnSize = count; return rnt;}
- 下面给出一个set的做法,由题解给出,侵删。
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { set<int> s(nums1.begin(), nums1.end()); vector<int> out; for (int x : nums2) if (s.erase(x)) out.push_back(x); return out;}
阅读全文
0 0
- leetcode 记录 349. Intersection of Two Arrays
- 349.[Leetcode]Intersection of Two Arrays
- [leetcode] 349. Intersection of Two Arrays
- Leetcode Everyday: 349. Intersection of Two Arrays
- leetcode.349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- Leetcode 349. Intersection of Two Arrays
- leetcode 349. Intersection of Two Arrays
- leetcode 349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- 【leetcode】 349. Intersection of Two Arrays
- Leetcode 349. Intersection of Two Arrays
- LeetCode 349. Intersection of Two Arrays
- Leetcode题解 349. Intersection of Two Arrays
- LeetCode - 349. Intersection of Two Arrays
- [Leetcode]349. Intersection of Two Arrays
- 349. Intersection of Two Arrays--LeetCode Record
- LeetCode 349. Intersection of Two Arrays
- Java疯狂讲义读书笔记第八章
- HDU
- The best way of parsing xml
- 非常详细的weblogic使用教程以及集群配置
- 将后台中获取的值传到select,并将左边select的值移到右边,将select的全部值传到后台
- LeetCode 349. Intersection of Two Arrays
- hdu 2029 Palindromes _easy version
- opencv总结1
- 使用TCP协议的NAT穿透技术 (转)
- 第一篇博客。
- 【JavaSE学习笔记】常用类介绍03_Character,Arrays,BigDecimal,BigInteger,Calendar
- 数据库的基本语句用法
- SpringBoot之使用JPA保存数据
- oracle Supplemental Log补全日志介绍