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

Source: Internet
Author: User



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, 11, 15], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 so return [0, 1];

The test wrote a relatively low, simple and rude, the code is as follows:
 
class test 
    {
        function __construct()
        {
            echo "邱二狗<br>";
        }
        public function a1($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 = new test();
$hc->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


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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.