昨天写的,今天直接附上代码
<span style="font-size:18px;">public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set numSet1=new HashSet();
Set numSet2=new HashSet();
for(int m =0;m<nums1.length;m++){
numSet1.add(nums1[m]);
}
for(int m =0;m<nums2.length;m++){
numSet2.add(nums2[m]);
}
ArrayList newList = new ArrayList();
List<Integer> list1 = new ArrayList<Integer>(numSet1);
List<Integer> list2 = new ArrayList<Integer>(numSet2);
int i=0,j =0;
Collections.sort(list1);
Collections.sort(list2);
while(i<list1.size()&&j<list2.size()){
if((list1.get(i)).equals(list2.get(j)) ){
newList.add(list1.get(i)) ;
i++;
j++;
}else if(list1.get(i) > list2.get(j)){
j++;
}else{
i++;
}
}
int ret[]=new int[newList.size()];
for(i=0;i<newList.size();i++)
{
ret[i]=((Integer)newList.get(i)).intValue();
}
return ret;
}
}</span>
set list map都没有int类型,所以想要输出int类型需要先转换成为Integer类型然后再进行转换
其次Arrays.asList这种方法对于转换array为list时,这种方法是将Array转换为list中的一项而不是一一对应的关系,值得注意
关于,set,list,map的总结灰写到java学习积累贴中,据说是面试中常见题。
2016/8/25