两数组的交 II
来源:互联网 发布:java page cache 编辑:程序博客网 时间:2024/05/16 07:44
问题描述:计算两个数组的交
样例:nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
解题思路:跟上面的数组的交类似,但是不同之处在于,每个元素出现次数得和在数组里一样。参考上一题的做法,我们依旧先对两个数组进行排序,再逐一比较两数组的元素。若数组1当中的元素小于当前位置数组2当中的元素,则此时数组2当中的指针保持不变,数字1当中的指针往后移;同理若数组1当中的元素大于数组2当中的元素,则数组1的指针不变,数组2的指针后移;若两个数组的当前位置的元素恰好相等,则把它加入到vector 向量当中。
实现代码:
class Solution {
public:
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
// Write your code here
vector<int> output;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int n1 = nums1.size();
int n2 = nums2.size();
int i=0, j=0;
int last = 0;
while(i<n1 && j<n2)
{
if(nums1[i] < nums2[j])
i++;
else if(nums1[i] > nums2[j])
j++;
else
{
output.push_back(nums1[i]);
i++;
j++;
}
}
return output;
}
};
做题感想:注意跟上一题的区别,怎样把所有的元素都加入vector 里,就是只要两个元素相等,就把它加进去。
- 两数组的交 II
- 两数组的交 II
- 两数组的交II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- 两数组的交 II
- LintCode:两数组的交 II
- LintCode 548 两数组的交 II
- LintCode【两数组的交II】
- 理解java字节码
- LeetCode 455. Assign Cookies
- 总结一个recyclerview使用模版
- 《Python数据分析与挖掘实战》笔记(三):数据探索
- 【BZOJ1833】【数位DP】 count 数字计数
- 两数组的交 II
- MySQL命令show full processlist
- 线程的调度&&线程的生命周期&&Daemon线程
- memset与memcpy的用法
- Maven从下载到eclipse建立项目
- JAVA---猜字游戏
- 暴力破解ssh远程登录
- mac终端下svn常用命令
- 计算机图形学