您的位置:首页 > 其它

Intersection of Two Arrays | & ||

2016-06-30 12:50 274 查看

Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

Example

Given nums1 =
[1, 2, 2, 1]
, nums2 =
[2, 2]
, return
[2]
.

分析:

这种考察一个数是否存在另一个集合中,一般来讲,都会用到HashSet. 如果不允许用额外的存储空间,可以对nums1排序,然后使用二分查找。

public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
int[] arr = new int[0];
return arr;
}

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i : nums1) {
if (map.containsKey(i)) {
map.put(i, map.get(i) + 1);
} else {
map.put(i, 1);
}
}

ArrayList<Integer>  list = new ArrayList<Integer>();

for (int i : nums2) {
if (map.containsKey(i) && map.get(i) >= 1) {
list.add(i);
map.put(i, map.get(i) - 1);
}
}
return convertIntegers(list);
}

public int[] convertIntegers(List<Integer> integers) {
int[] ret = new int[integers.size()];
Iterator<Integer> iterator = integers.iterator();
for (int i = 0; i < ret.length; i++) {
ret[i] = iterator.next().intValue();
}
return ret;
}
}


View Code
转载请注明出处:cnblogs.com/beiyeqingteng/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: