希望能坚持每天做些题 :>
Day1
1、Two Sum
给定一个整形数组,返回加在一起的和等于目标值的两个数在数组中的位置。
你可以假设每个输入均只有一个特定的输出,并且你不能使用同一个元素两次。
示例:
给定数组 nums = [2, 7, 11, 15],target = 9,
因为 nums[0] + nums[1] = 2 + 7 = 9,
故返回 [0, 1]
基本思路有二:
1、时间复杂度为O(n^2),即循环嵌套。
2、时间复杂度为O(n),通过哈希表将每次查找(比如说目标值为9,当前值为2,需要7,7即为互补的数)互补的数的时间缩短由O(n)为O(1),步骤是先创建这样的一个哈希表,时间复杂度O(n),再循环原来的数组,逐个查找存在的哈希表中是否包含互补的数,并且索引与当前值不同的。
Java的解法,用时9ms,优于75.5%的运行时间
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
for(int i = 0; i < nums.length; i++){
int comp = target - nums[i];
if(map.containsKey(comp) && map.get(comp) != i){
return new int[] {i, map.get(comp)};
}
}
throw new IllegalArgumentException("No such sum");
}
}
python的解法,48ms,优于52.86%的运行时间,思路和java的一样,都是第二种思路,没有直接用哈希表,而是用了python内置的数据结构字典,字典的实现方法和哈希表类似,但是运行的时间并不是特别好吧,还不知道更好的应该怎么实现 :<
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
map = {nums[i]: i for i in range(len(nums))}
for i in range(len(nums)):
comp = target - nums[i]
if comp in map and map[comp] != i:
return [i, map[comp]]