Objective
Today, the process of completing an algorithm, there are several requirements module, which has to determine whether a $ A array is a subset of $b array, perhaps recently I write C more, directly with the For loop implementation, but feel the code is larger, not elegant! In the QQ group brainstorming a bit, found that many of the system functions provided by PHP can be called, here to record
Demand
Minimum time complexity to determine if a $ A array is a subset of the $b array
[PHP]
Quickly determine if a $ A array is a subset of the $b array
$a = array (135,138);
$b = Array (135,138,137);
Quickly determine if a $ A array is a subset of the $b array
$a = array (135,138);
$b = Array (135,138,137);
Implementation method
Here are three ways to approach, the idea is actually the same, the difference lies in the implementation of the Code
For loop traversal
[PHP]
$flag = 1;
foreach ($a as $va) {
if (In_array ($va, $b)) {
Continue
}else {
$flag = 0;
Break
}
}
if ($flag) {
echo "Yes";
}else {
echo "No";
}
$flag = 1;
foreach ($a as $va) {
if (In_array ($va, $b)) {
Continue
}else {
$flag = 0;
Break
}
}
if ($flag) {
echo "Yes";
}else {
echo "No";
}
Use of Array_diff
Code
[PHP]
$c = Array_diff ($a, $b);
Print_r ($c);
$flag = Empty ($c)? 1:0;
if ($flag) {
echo "Yes";
}else {
echo "No";
}
$c = Array_diff ($a, $b);
Print_r ($c);
$flag = Empty ($c)? 1:0;
if ($flag) {
echo "Yes";
}else {
echo "No";
}
Use of Array_intersect
Code
[PHP]
if ($a = = Array_intersect ($a, $b)) {
$flag = 1;
}else {
$flag = 0;
}
if ($flag) {
echo "Yes";
}else {
echo "No";
}
if ($a = = Array_intersect ($a, $b)) {
$flag = 1;
}else {
$flag = 0;
}
if ($flag) {
echo "Yes";
}else {
echo "No";
}
Postscript
A good mentor can not only teach me how to learn, but also teach me how to do things, be grateful, have the responsibility
http://www.bkjia.com/PHPjc/477471.html www.bkjia.com true http://www.bkjia.com/PHPjc/477471.html techarticle Preface the process of completing an algorithm today, there are several requirements module, in which there is a judge of a $ A array is a subset of $b array, perhaps recently I write C more, directly with the For loop implementation ...