Status message

Maintenant, vous regardez: 1. Two Sum

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

  1. Given nums = [2, 7, 11, 15], target = 9,
  2. Because nums[0] + nums[1] = 2 + 7 = 9,
  3. return [0, 1].

Structure

  1. class Solution {
  2.  
  3. /**
  4.   * @param Integer[] $nums
  5.   * @param Integer $target
  6.   * @return Integer[]
  7.   */
  8. function twoSum($nums, $target) {
  9. //code goes here
  10. }
  11. }

One Solution:

  1. class Solution {
  2. /**
  3.   * @param Integer[] $nums
  4.   * @param Integer $target
  5.   * @return Integer[]
  6.   */
  7. function twoSum(array $nums, int $target) : array {
  8. $map = [];
  9. for ($i = 0; $i < count($nums); $i++) {
  10. $map[$nums[$i]] = $i;
  11. }
  12. for ($i = 0; $i < count($nums); $i++) {
  13. $complement = $target - $nums[$i];
  14. if (array_key_exists($complement, $map) && $map[$complement] != $i) {
  15. return [$i, $map[$complement] ];
  16. }
  17. }
  18. throw new IllegalArgumentException("No two sum solution");
  19. }
  20. }
  21.  
  22. $instance = new Solution();
  23.  
  24. $result = $instance->twoSum([2, 7, 11, 15, 20], 26);
  25.  
  26. print_r($result);

Output:

  1. (
  2. [0] => 2
  3. [1] => 3
  4. )