Perl-求交集和并集(Nvidia2018笔试)
1、原题
2、代码
@A = (5,6,7); # 数组用@和圆括号,用$A[index]访问;哈希用%和圆括号,用 # $A{‘key‘}访问 @B = (6,7,8); @intersection; @union; # 计算交集,依次取出A中元素,判断其是否与B中的某个元素相等 foreach $a (@A){ for($i=0;$i<@B;$i++){ # @B的含义由上下文决定,此处表示其size if($B[$i] == $a){ push(@intersection,$a); } } } print("intersection is:\n"); foreach $item (@intersection){ print("$item "); } print("\n"); # 计算并集,先将A和B直接合并,接着依次判断A_B中的各个元素是否已经存在于 # 当前的union数组中,若没有则push进去 @A_B = (@A,@B); for $item (@A_B){ $item_in_current_union = 0; for($i=0;$i<@union;$i++){ if($union[$i]==$item) { $item_in_current_union = 1; } } if($item_in_current_union == 0){ push(@union,$item); $size = @union; # union的大小动态改变 print("union size is $size\n"); } } print("union is:\n"); foreach $item (@union){ print("$item "); } print("\n");
3、输出
intersection is: 6 7 union size is 1 union size is 2 union size is 3 union size is 4 union is: 5 6 7 8
相关推荐
边城客栈学无止境 2020-07-05
Walter的学习笔记 2020-07-04
A宇 2020-06-14
边城客栈学无止境 2020-06-10
邓博学习笔记 2020-06-03
davidliu00 2020-05-26
ShiShuo 2020-05-16
Aggressivesnail 2020-05-10
ShiShuo 2020-04-26
hanxingwang00 2020-04-22
davidliu00 2020-03-06
ShiShuo 2020-03-06
Aggressivesnail 2020-02-28
aaLiweipeng 2020-02-01
amberom 2020-01-16
Walter的学习笔记 2020-01-06
Aggressivesnail 2019-12-31