您的位置:首页 > 其它

lintcode:两个数组的交

2016-07-07 09:56 253 查看
题目

返回两个数组的交

样例

nums1 =
[1, 2, 2, 1]
, nums2 =
[2, 2]
, 返回
[2]
.

解题

排序后,两指针找相等元素,注意要去除相同的元素

public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
Arrays.sort(nums1);
Arrays.sort(nums2);
ArrayList<Integer> A = new ArrayList<Integer>();
int i=0;
int j=0;
while(i<nums1.length && j<nums2.length ){
if(nums1[i] == nums2[j]){
A.add(nums1[i]);
i++;
j++;

}else if(nums1[i] < nums2[j]){
i++;
}else{
j++;
}
int tmpi = i;
int tmpj = j;
// 去重
while(i+1<nums1.length && nums1[i]==nums1[i+1]) i++;
while(j+1<nums2.length && nums2[j]==nums2[j+1]) j++;
// 没有重复,按照上面更新的i 和 j
if(tmpi<nums1.length && tmpi ==i){
i= tmpi;
}
if(tmpj<nums2.length && tmpj ==j){
j = tmpj;
}
}
int[] res = new int[A.size()];
for( i=0;i<A.size();i++){
res[i] = (int)A.get(i);
}
return res;
}
}


利用HashMap

将数组1的值唯一的保存在map中

根据map在去重

public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();

for(int i =0;i<nums1.length;i++){
if(!map.containsKey(nums1[i])){ // 唯一映射
map.put(nums1[i],1);
}
}
ArrayList<Integer> A = new ArrayList<Integer>();
for(int i=0;i<nums2.length;i++){
if(map.containsKey(nums2[i])){ // 相同元素
A.add(nums2[i]);
map.remove(nums2[i]); // 去除相同元素
}
}
int[] res = new int[A.size()];
for(int i=0;i<A.size();i++){ // 保存到数组中
res[i] = A.get(i);
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: