您的位置:首页 > 其它

LeetCode笔记1--Two Sum

2017-06-30 09:56 316 查看
LeetCode的第一篇文章,希望通过这个系列的笔记能够提升自己的编码能力和算法能力。

问题描述(原文):

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.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


本人翻译:给你个int数组,返回两个相加等于特定值的数组元素下标。你可以假设每个输入都会有一个确定的解决方法,也可能不会用两次相同的元素。说实话最后半句我也没明白啥意思,如果有知道的,可以在文章下边留言,many thanks.

Solution:
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> mapping = new HashMap<>();
int[] indesx = new int[2];
for (int i = 0; i < nums.length; i++) {
mapping.put(nums[i], i);
}

for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (mapping.containsKey(complement) && mapping.get(complement) != i) {
indesx[0] = nums[i];
indesx[1] = complement;
}
}

return indesx;
}

总结:

在这里声明一下,虽然文章是原创,但是Solution并非我写的代码,上段代码引用了LeetCode上此问题支持率最高的解决方法。

看到题目的时候我是正常的用了二重for循环进行求解的,在LeetCode中也有我那种解法,他们称之为:Brute Force。

而上面贴出来的这种解法思路在于考虑到了时间复杂度。这里又不得不记录一下我收集到了对时间复杂度的理解:

基本操作执行次数与问题规模n成正比。时间复杂度(又叫渐进时间复杂度,我的理解其实就是求极限值)共有八个同数量级分别是:1,log2n,n,n
log2n,n^2,n^3,2^n,n!
  从1到n!时间复杂度以此增高。二重for循环记作O(n^2),三重for循环记作O(n^3)以此类推。

解释是这样的:To improve
our run time complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to look up its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.

为了改进我们运行时间的复杂程度,我们需要更有效的方法去array中检查是否有一个特定的“补足数”存在,如果存在,我们就去找他的index。那么维护数组元素与其下标之间的映射关系最好的途径是什么呢?没错,就是hash
table。

这句话给我的印象特别深。那么如果下一次又出现一个问题要求我们找到两组值的对应关系的话,我们首先就会考虑到哈希表。这正是我希望得到的东西,一种思考的方向。

We reduce the look up time from O(n)
to O(1) by trading space for speed. A hash table is built exactly for this purpose, it supports fast look up in near constant time. I say "near" because if a collision occurred, a look up could degenerate to O(n) time. But look up in hash table should be amortized
O(1) time as long as the hash function was chosen carefully.

我们通过牺牲空间换取速度的方式来将时间复杂度从O(n)到O(1)。哈希表的建立正是为此目的,它支持在近乎不变的时间内快速查找。

后面我就不翻译了,因为我并没有理解他的意思。有兴趣的朋友欢迎文章下方留言。不胜感激。

===================================================================================================================

2017-7-2,补充

刚刚在研究HashSet的时候得知了HashSet的相关特性,不允许重复的元素,允许null值,等等,不过这不是关键,关键的是返回来看HashMap,原来也是不能有重复Key的,如果有相同的Key,那么就会被新的Key所覆盖。因此,这就可以解释you
may not use the same element twice.这句话了,如果有重复的int数值,那么就会产生覆盖的问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: