[LeetCode] 1. Two Sum

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 same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

两数之和。

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

你可以按任意顺序返回答案。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

暴力解是O(n^2)级别的复杂度,一定会超时。为了不超时,我们使用hashmap记录每个元素和他的下标。找的时候是在找 hashmap 里是否存在能组成target的另一个数字 target - nums[i]。

LC里面有一部分题目也是需要通过 hashmap 或者 two pointer 来加快运行速度的,我总结在这个tag里了。

时间O(n)

空间O(n)

JavaScript实现

 1 /**
 2  * @param {number[]} nums
 3  * @param {number} target
 4  * @return {number[]}
 5  */
 6 var twoSum = function (nums, target) {
 7     let map = {};
 8     const len = nums.length;
 9     for (let i = 0; i < len; i++) {
10         let cur = nums[i];
11         let complement = target - cur;
12         if (map[complement] !== undefined) {
13             return [map[complement], i];
14         }
15         map[cur] = i;
16     }
17 };

 

Java实现

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         // corner case
 4         if (nums == null || nums.length == 0) {
 5             return new int[] {-1, -1};
 6         }
 7         // normal case
 8         HashMap<Integer, Integer> map = new HashMap<>();
 9         for (int i = 0; i < nums.length; i++) {
10             if (map.containsKey(target - nums[i])) {
11                 return new int[] {map.get(target - nums[i]), i};
12             }
13             map.put(nums[i], i);
14         }
15         return new int[] {-1, -1};
16     }
17 }

 

python3实现

1 class Solution:
2     def twoSum(self, nums: List[int], target: int) -> List[int]:
3         hashmap = dict()
4         for i, num in enumerate(nums):
5             if target - num in hashmap:
6                 return [hashmap[target - num], i]
7             hashmap[nums[i]] = i
8         return [-1, -1]

 

two sum题目总结

LeetCode 题目总结

posted @ 2019-10-08 10:15  CNoodle  阅读(720)  评论(0编辑  收藏  举报