Title
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:
1 | Given nums = [2, 7, 11, 15], target = 9, |
anwser
1 | /** |
显而易见,最low的解法,因为是刚开始做,尝试进行优化无果后去查看官方的解法,恍然大悟,原来可以用hashmap等容器进行辅助,将时间复杂度由O(n^2)降低到O(n),先来看代码:
1 | public int[] twoSum(int[] nums, int target) { |
上述代码是用java写的,主要是通过遍历一遍数组,得到一个map,然后从里面找到target与num[i]的差值,这里简单的应用了hashmap就完成了复杂的操作,也是我们需要灵活运用数据结构的例子。
这里虽然上面已经做到很快,但是在进行之前还是需要先轮训一遍数组,我们是不是可以省去这一步呢,这时候有了第三种方法,同样的,我们先来看代码:
1 | public int[] twoSum(int[] nums, int target) { |
通过上述代码我们可以看到巧妙的地方,只是走了一遍轮训,在这个过程中找到hashmap中是否由差值,如果没有就存进去
总结
这道题很简单,但是让我看到了hashmap在某些算法场景下能带来的巨大改进,同时也看到了巧妙的运用代码可以更高效的完成我们的操作,以后写算法看来不能全都用c语言了,毕竟容器的实现并不是我们刷题的重点。