题意

image.png

解题思路:

  • 暴力破解: Time: O(n^2), Space: O(1)
  • 哈希表: Time: O(n), Space: O(n)

PHP 代码实现

  1. class Solution {
  2. function twoSum($nums, $target) {
  3. $map = [];
  4. for ($i = 0; $i < count($nums); $i++) {
  5. $needNum = $target - $nums[$i];
  6. if (isset($map[$needNum])) return [$map[$needNum], $i];
  7. $map[$nums[$i]] = $i;
  8. }
  9. return [0, 0];
  10. }
  11. function twoSumByBruteForce($nums, $target) {
  12. for ($i = 0; $i < count($nums); $i++) {
  13. for ($j = $i + 1; $j < count($nums); $j++) {
  14. if ($nums[$i] + $nums[$j] == $target) return [$i, $j];
  15. }
  16. }
  17. }
  18. }

GO 代码实现

  1. func twoSum(nums []int, target int) []int {
  2. twoSum1(nums, target)
  3. tmp, res := make(map[int]int,0),[]int{}
  4. for _, v := range nums{
  5. if _, ok := tmp[target - v]; ok {
  6. res = append(res, v, tmp[target - v])
  7. return res
  8. }
  9. tmp[v] = v
  10. }
  11. return res;
  12. }
  13. func twoSumByBruteForce(nums []int, target int) []int {
  14. for i := 0; i < len(nums); i++ {
  15. for j := i+1; j < len(nums); j++ {
  16. if nums[I] + nums[j] == target {
  17. return []int{i, j}
  18. }
  19. }
  20. }
  21. return nil
  22. }