算法题两数之和

25次阅读

共计 583 个字符,预计需要花费 2 分钟才能阅读完成。

题目描述:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例

给定 nums = [2,4,5,6], target = 9
因为 nums[1] + nums[2] = 4 + 5 = 9
所以返回 [1, 2]

方法一:暴力法
遍历每个元素 item, 查找是否存在一个值与 target-item,相等的元素

var twoSum = function(nums, target) {for(let i=0;i<nums.length;i++){for(let j=i+1;j<nums.length;i++){if(nums[j]==target-nums[i]){return [i,j]
            }
        }
    }
};

时间复杂度:O(n2)
方法二:一次循环
遍历每个元素 item, 查找是否存在一个值与 target-item,相等的元素

var twoSum = function(nums, target) {for(let i=0;i<nums.length;i++){let temp=target-nums[i];
        let index = nums.indexOf(temp,i+1);
        if (index != -1) {return [i, index]
        }
    }
};

时间复杂度:O(n)

正文完
 0

算法题两数之和

25次阅读

共计 1224 个字符,预计需要花费 4 分钟才能阅读完成。

1. Two Sum

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.

Example:


Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

一、两遍循环,暴力破解

代码如下

function twoSum($nums, $target) {for($i=0;$i<count($nums); $i++){for($j=$i+1; $j<count($nums); $j++){$sum = $nums[$i]+$nums[$j];
                if($target == $sum){return array($i,$j);
                }
            }
        }
    }

时间复杂度 O(n^2)

提交,结果执行时间 1968 ms。。。。。
可以说龟速了

二、两遍 hash

这个方法是看了 leetcode 的解决方案,但它是 java 代码,开始不知道,其实 php 的数组就是 hash 实现的,后面看了下面两片文章的介绍,才理解,解决的。
https://www.cnblogs.com/s-b-b…
https://www.cnblogs.com/shang…

代码如下

function twoSum2(array $nums , $target)
{$res = [];
    $nums_match = [];
    foreach ($nums as $nums_k => $nums_v){if(!isset($nums_match[$target-$nums_v])){$nums_match[$target-$nums_v] = $nums_k;
        }
    }
    
    foreach ($nums as $nums_k => $nums_v){if (isset($nums_match[$nums_v]) && $nums_match[$nums_v] != $nums_k) {$res[] = $nums_k;
            $res[] = $nums_match[$nums_v];
            return $res;
        }
    }
}

时间复杂度 O(n)
执行时间 24 ms,提升很大

三、一遍 hash

这是在两边 hash 的基础上进行的优化

代码如下

function twoSum($nums, $target) {$nums_match = [];
        foreach ($nums as $nums_k => $nums_v){if((isset($nums_match[$target-$nums_v]))){return array($nums_match[$target-$nums_v],$nums_k);
            }
            $nums_match[$nums_v] = $nums_k;
        }

    }

时间复杂度 O(n)
执行时间 16 ms

正文完
 0