Home > Backend Development > PHP Tutorial > PHP determines whether the same number exists in two ordered arrays sample code analysis

PHP determines whether the same number exists in two ordered arrays sample code analysis

黄舟
Release: 2023-03-06 18:06:01
Original
1426 people have browsed it

PHP determines whether the same number exists in two ordered arrays Sample code analysis

<?php
$len1 = sizeof($arr1);
$len2 = sizeof($arr2);

$flag = false; //用来退出外层循环
$start = 0;
$counter = 0;

for($i = 0; $i < $len1; $i++) {
	if($flag) {
		break;
	}
	
	// $start 记录上次循环到的索引
	for($j = $start; $j < $len2; $j++) {
		if($arr2[$j] == $arr1[$i]) {
			echo &#39;find, &#39;, $arr2[$j];
			$flag = true;
			break;
		}

		// 用 $counter 来控制次数,当前内循环中仅记录一次
		if($arr2[$j] > $arr1[$i] && $counter == 0) {
			$start = $j;
			$counter++;
		}
	}

	$counter = 0; //下一次循环开始,重置为0
}
Copy after login

Method 2:

Idea: First set two subscripts, initialize them to the starting addresses of the two arrays, and advance forward in sequence. The rule of advancement is to compare the numbers in the two arrays. The subscript of the smaller array is pushed forward one step further until the subscript of any array reaches the end of the array. If the same number has not been encountered at this time, it means that the subscript in the array is There are no identical numbers.

<?php
$i = $j = 0;
$len1 = count($arr1);
$len2 = count($arr2);
while($i < $len1 && $j < $len2) {
	if($arr1[$i] == $arr2[$j]) {
		echo &#39;find, &#39;, $arr1[$i];
		break;
	}
	
	if($arr1[$i] > $arr2[$j]) {
		$j ++;
	}
	else {
		$i ++;
	}
}
Copy after login

The above is the detailed content of PHP determines whether the same number exists in two ordered arrays sample code analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template