Leetcode01. 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
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解法
- 暴力穷举,使用双重循环查找和为target的元素。时间复杂度 O ( n 2 ) O(n^2) O(n2),空间复杂度 O ( 1 ) O(1) O(1)。
- 使用哈希表,在向哈希表插入元素num的同时查找哈希表中是否存在target - num元素。时间复杂度为O(n^),空间复杂度为O(n)。key为数组元素值,value是数组元素的下标。
Java
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();//新建哈希表
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {//containsKey()方法来判断是否存在键complement,时间复杂度O(1)
return new int[] { map.get(complement), i };//get()方法返回指定key的值
}
map.put(nums[i], i);//put()方法向哈希表中插入key与value
}
throw new IllegalArgumentException("No two sum solution");
}
}
Python
class Solution:#820ms
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_list = enumerate(nums) #enumerate(sequence, [start=0]),[数据下标,数据]
for idx,n in nums_list:
if (target - n) in nums[idx+1:]:#在剩余元素中查找target-n
return [idx,nums[idx+1:].index(target-n)+idx+1]#返回n的下标与target-n的下标
return None
class Solution:#48ms
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for x in range(0,len(nums)-1):
if nums[x] in dic:
return [dic[nums[x]],x]
else:
dic[target-nums[x]]=x
C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
for(int i = 0; i < nums.size(); i++){
if(m.count(nums[i])) //count()返回的是被查找元素的个数,map中不存在相同元素
return {m[nums[i]], i};
m[target - nums[i]] = i;
}
return {-1, -1};
}
};