题目:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
解析
来源于Leetcode 讨论区
/*
思路:
使用set,先把num1数组的数都传给set类型的record
重复也没关系,set只会存储一个
然后使用contain,查询num2是否那个数据在record里
存储在resultSet里
然后返回一个数组
*/
class Solution05 {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> record = new HashSet<>();
Set<Integer> resultSet = new HashSet<>();
for(int i = 0; i < nums1.length; i++){
record.add(nums1[i]);
}
for(int i = 0; i < nums2.length; i++){
if(record.contains(nums2[i])){
resultSet.add(nums2[i]);
}
}
int intArray[] = new int[resultSet.size()];
int i = 0;
for(Integer num : resultSet){
intArray[i] = num;
i++;
}
return intArray;
}
}
最近老是遇到各类型转化,总结一下:
String转换为int类型的方法:
1. Integer.parseInt([String])
2.Integer.valueOf([String]).intValue();
注: 字串转成 Double, Float, Long 的方法大同小异.
>
int转换为String类型方法:
1.String s = String.valueOf(i);
2.String s = Integer.toString(i);
3. String s = “” + i;
注: Double, Float, Long 转成字串的方法大同小异.
>
object类型转换为int类型:
1.如果object是byte,short,int,char类型生成的,那么不用转换直接赋值就ok了。
2.如果object是字符串类型生成的,先把object转换为String类型的,再把String类型转换为int类型。
例如.
String myInt=”123”;
Object os=myInt;
int b=Integer.parseInt((String)os);//还可以os.toString()
3.如果object是float,double,long类型生成的,思路和上面一样,先把object转换为相应的数据类型,然后再转换为int类型。
>
object类型转换为String类型:
String title=String.valueOf(obj[2]);
String content=String.valueOf(obj[3]);
>
//这里把数组值传给ArraryList
nonZeroElement.add(Integer.toString(nums[i]));
//这里把ArraryList传给数组
nums[i] = Integer.parseInt(nonZeroElement.get(i));