Given an array of integers, return indices of the two numbers such that they add up to a specific target.php
You may assume that each input would have exactly one solution, and you may not use the same element twice.html
Example:java
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。。。。。
能夠說龜速了code
這個方法是看了leetcode的解決方案,但它是java代碼,開始不知道,其實php的數組就是hash實現的,後面看了下面兩片文章的介紹,才理解,解決的。
https://www.cnblogs.com/s-b-b...
https://www.cnblogs.com/shang...htm
代碼以下blog
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 ,提高很大ci
這是在兩邊hash的基礎上進行的優化element
代碼以下
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