Leetcode350. Intersection of Two Arrays II
来源:互联网 发布:sql server 导出数据库 编辑:程序博客网 时间:2024/06/16 16:33
一、原题
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2, 2]
.
二、思路
与之前求两数组的重叠部分不同,这次要求交集可以有重复的元素。
首先将两个数组进行排序
然后遍历两个数组,使用变量i 和j 分别指向两个数组,遍历两个数组的元素是否相同。如果相同,则放在集合中;如果前者小,则i后移;若后者小,则j后移
要点:将数组排序,list集合和数组转换,
三、代码
public class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
//首先将num1、num2排序
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer>list=new ArrayList<>();
for(int i=0,j=0;i<nums1.length&&j<nums2.length;){
if(nums1[i]==nums2[j]){
list.add(nums1[i]);
i++;
j++;
}
else if (nums1[i]<nums2[j]) {
i++;
}
else {
j++;
}
}
//将list集合中的数据转化为数组
int[]nums=new int[list.size()];
for (int k = 0; k < list.size(); k++) {
nums[k]=list.get(k);
}
return nums;
}
}
public int[] intersect(int[] nums1, int[] nums2) {
//首先将num1、num2排序
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer>list=new ArrayList<>();
for(int i=0,j=0;i<nums1.length&&j<nums2.length;){
if(nums1[i]==nums2[j]){
list.add(nums1[i]);
i++;
j++;
}
else if (nums1[i]<nums2[j]) {
i++;
}
else {
j++;
}
}
//将list集合中的数据转化为数组
int[]nums=new int[list.size()];
for (int k = 0; k < list.size(); k++) {
nums[k]=list.get(k);
}
return nums;
}
}
0 0
- Leetcode350. Intersection of Two Arrays II
- Leetcode350. Intersection of Two Arrays II
- LeetCode350. Intersection of Two Arrays II
- leetcode350~Intersection of Two Arrays II
- leetcode350. Intersection of Two Arrays II
- Leetcode350 - Intersection of Two Arrays II(two pointers)
- Leetcode350. Intersection of Two Arrays II很简单的做法
- Leetcode350 Intersection of Two Arrays II &Leetcode Intersection of Two Arrays
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Python中try...except...else的用法
- ViewStub 测试Demo By Terry
- 在windows上通过浏览器远程连接Linux服务器的jupyter
- java自定义注解
- 关于微信H5公众号支付我们踩过的坑(get_brand_wcpay_request:fail)(防止更多人踩坑)
- Leetcode350. Intersection of Two Arrays II
- JUnit学习
- org.springframework.data.repository.core.support.DefaultRepositoryMetadata
- -Dmaven.multiModuleProjectDirectory system propery is not set.
- Workspace default 的JRE System Library与Project的JRE System Library
- UIWindow基础知识详解
- 配置SharePoint 2016开发环境的时候遇到的两个问题
- Hive分区、分桶操作及其比较
- HDU-5744 Keep On Movin(回文串 贪心)