Tuesday, March 22, 2022

[LeetCode] 1. Two Sum

"踏上LeetCode解題之路,順手紀錄一下PHP練功的過程囉。這是第一篇~~"


Two Sum - LeetCode


題目要求

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

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.


思考過程

  1. 先取得$nums的陣列長度
  2. 確認$target減去某數值後的$j數值(某兩數值相加的意思)
  3. 數值$j確認存在於陣列中
  4. 回傳$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; } } }

Contact Form

Name

Email *

Message *