PHP实现数组中两个数的和等于给定的目标值

算法: 
1、以数组中的值为索引创建新的数组$tmp 
2、求出目标值减去数组值得差值 
3、判断该差值是否在\$tmp中。 
php实现代码如下

/**
 * Given an array of integers, return indices of the two numbers such that they add up to a specific target.
 * You may assume that each input would have exactly one solution, and you may not use the same 
 * element twice.
 * Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
 * @param  [type] $arr [description]
 * @param  [type] $sum [description]
 * @return [type]      [description]
 */
function twoSum($arr, $sum) {
    $len = count($arr);
    if ($len < 2) return false;
    $tmp = [];
    $flag = [];
    // 以数组的值为索引
    for ($i = 0; $i < $len; $i++) {
        $tmp[$arr[$i]] = $i;
    }
    // 判断差值是否在上述索引数组中
    for ($j = 0; $j < $len; $j++) {
        $minus = $sum - $arr[$j];
        if ($minus < 0 || $sum <= $arr[$j]) continue;
        if (isset($tmp[$minus]) && !isset($flag[$arr[$j]]) && !isset($flag[$minus])) {
            echo '数组的索引值为[' . $tmp[$arr[$j]] . ',' . $tmp[$minus] . ']<br>';
            // 如果有则将值置为1
            $flag[$arr[$j]] = 1;
        }
    }
}
$arr = [2, 7, 11, 15];
//$arr = [1,2,7,9,8,3,6,5,4,10];
twoSum($arr, 9);
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

时间复杂度为O(n)。


来源:http://blog.csdn.net/fationyyk/article/details/75228347

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值