Preface
During the process of completing an algorithm today, there are several required modules in which we can determine whether the $ a array is a subset of the $ B array. Maybe I have written many c statements recently, the for loop is implemented directly, but the code volume is large and not elegant enough! I made a wide discussion in the QQ group and found that many system functions provided by php are available for calling. Record them here.
Requirement
Determine whether the $ a array is a subset of the $ B Array Based on the minimum time complexity.
[Php]
// Quickly determine whether the $ a array is a subset of the $ B Array
$ A = array (135,138 );
$ B = array (135,138,137 );
// Quickly determine whether the $ a array is a subset of the $ B Array
$ A = array (135,138 );
$ B = array (135,138,137 );
Implementation Method
The three methods are introduced here, with the same idea. The difference lies in the implementation 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 with gratitude and responsibility.