PHP求两数之和

  • Post author:
  • Post category:php


该方法使用hash表的思想去解答

$nums = [11,15,2,7];
$target = 9;

$num_array = [];

function twoSum($nums, $target) {
	foreach($nums as $key=>$val){
		
		if(!isset($num_array[$target - $val ])){
			$num_array[$val] = $key;
		}
		
		if(isset($num_array[$target - $val ])){
			$result = [ $num_array[$target - $val ],$key]
			break;
		}
	}
}



版权声明:本文为sinat_33801009原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。