Leetcode - 349 - Intersection of Two Arrays - 类型转化,String<->int,object<->int

本文介绍了一个简单的算法,用于计算两个整数数组的交集,并确保结果中的每个元素都是唯一的。通过使用HashSet数据结构来实现这一目标,提高了查找效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值