Home  >  Article  >  Backend Development  >  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

黄舟
黄舟Original
2017-03-18 09:49:591345browse

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
}

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 ++;
	}
}

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!

Statement:
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