PHP (1) "Sum of two numbers" algorithm problem

Source: Internet
Author: User

Tags: integer new equals const BSP strong Lin Array target

The original topic is this: given an array of integers and a target value, find the two numbers in the array and the target values. You can assume that each input corresponds to only one answer, and that the same element cannot be reused.

 Eg: given nums = [2, 7, one, +], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 so return [0, 1];

The test wrote a relatively low, simple and rude code as follows:
classTest {
function__construct () {Echo"Qiu Two dog <br>"; } Public functionA1 ($arr,$target) { $length=Count($arr); for($i= 0;$i<$length;$i++) { for($j=$i+1;$j<$length;$j++) { if($arr[$i]+$arr[$j] ==$target) { $b=Array($i,$j); Var_dump($b); return $b; } } } } }$HC=Newtest ();$HC-&GT;A1 (Array(2,3,4,5,6), 9);

The test result Array (1,4), the main idea is to iterate over each number in the array, in the array, see if it and its own number after the addition is equal to target.

PHP (1) "Sum of two numbers" algorithm problem

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: