题意:

image.png

解题思路:

  1. 思路:双指针
  2. 1. 使用两个指针left从左向右,right从右向左,移动之前比较target
  3. 2. 大于target则左移right--,小于则左移left++

PHP代码实现:

  1. class Solution {
  2. /**
  3. * @param Integer[] $numbers
  4. * @param Integer $target
  5. * @return Integer[]
  6. */
  7. function twoSum($numbers, $target) {
  8. $map = [];
  9. foreach ($numbers as $k => $v) {
  10. $diff = $target - $v;
  11. if (isset($map[$diff])) return [$map[$diff] + 1, $k + 1];
  12. $map[$v] = $k;
  13. }
  14. return $map;
  15. }
  16. function twoSumO1($numbers, $target) {
  17. $left = 0;
  18. $right = count($numbers) - 1;
  19. while ($left < $right) {
  20. $sum = $numbers[$left] + $numbers[$right];
  21. if ($sum == $target) {
  22. return [$left + 1, $right + 1];
  23. } else if ($sum > $target) {
  24. $right--;
  25. } else {
  26. $left++;
  27. }
  28. }
  29. return [];
  30. }
  31. }

go代码实现:

  1. func twoSum(numbers []int, target int) []int {
  2. twoSumO1(numbers, target)
  3. l, r := 0, len(numbers) - 1
  4. for l < r {
  5. sum := numbers[l] + numbers[r]
  6. if sum == target {
  7. return []int{l + 1, r + 1}
  8. } else if sum > target {
  9. r--
  10. } else {
  11. l++
  12. }
  13. }
  14. return []int{}
  15. }
  16. func twoSumO1(numbers []int, target int) []int {
  17. m := map[int]int{}
  18. for i, v := range numbers {
  19. diff := target - v
  20. if index, key := m[diff]; key {
  21. return []int{index + 1, i + 1}
  22. }
  23. m[v] = i
  24. }
  25. return []int{}
  26. }