![]() |
"踏上LeetCode解題之路,順手紀錄一下PHP練功的過程囉。這是第一篇~~" |
題目要求
Given an array of integers
nums
and an integertarget
, return indices of the two numbers such that they add up totarget
.You may assume that each input would have exactly one solution, and you may not use the sameelement twice.
You can return the answer in any order.
思考過程
- 先取得$nums的陣列長度
- 確認$target減去某數值後的$j數值(某兩數值相加的意思)
- 當數值$j確認存在於陣列中
- 回傳$i位於陣列中的位置
結果 ✅
class Solution { /** * @param Integer[] $nums * @param Integer $target * @return Integer[] */ function twoSum($nums, $target) { $lenth = count($nums); $array = []; for($i=0; $i<$lenth; $i++){ $j= $target-$nums[$i]; if(array_key_exists($j, $array)) return [$array[$j], $i]; $array[$nums[$i]] = $i; } } }