您的位置:首页 > 其它

LeetCode刷题:第1题Two Sum

2018-02-28 10:18 441 查看
听从老姐的建议,开始在LeetCode上刷题,争取每周能保质保量的完成2到3道题,针对有技巧的题目,我会以博客的形式将其中的原理以及各种算法都展现出来。所有题目请参考我的GitHub:GitHub地址

**题目要求:**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].

思路1:题目要求让我们在一个数组中找到两个不重复的数,并且和为target,输出两个数的下标。思路就是两重循环,外层i从第一个数,内层j每次从最后一个数开始,往前面走,遇到i就停止,跳出的条件为i,j两数之和为target。这个思路比较简单,很容易理解,但是相对的时间复杂度就很高,两重循环的时间复杂度为O(n^2)。

实现代码:

class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for(int i=0;i<nums.length-1;i++){
for(int j=nums.length-1;j>i;j--){
if(nums[i]+nums[j] == target){
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
}


思路2:其实这个思路我自己并没有想到,在借鉴题目附带的solution之后,才恍然大悟。思路1中我们讲到最直接的蛮力法就是两重循环,相对的时间复杂度也到达了O(n^2),所以为了减少时间复杂度,我们需要一种更加有效的方法检查数组中是否存在补码,即相对于nums[i],其补码为target-nums[i],假设存在这样的补码,其索引为j,为了满足题目要求,此时的i和j不能为同一个数。如果存在我们只需得到它的索引(下标)即可,而查找这种索引的的映射最佳方法是散列表,这个过程也就是空间换取时间的做法。因为哈希表支持在接近恒定时间内快速查找,所谓“近”的意思就是如果发生碰撞,时间复杂度可能退化到O(n),所以需要仔细选择散列函数就能保证近O(1)查找的时间复杂度。

实现代码:

class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i <= nums.length - 1; i++)
map.put(nums[i], i);
for(int i = 0;i<nums.length;i++){
int complement = target -nums[i];
if(map.containsKey(complement) && map.get(complement)!=i){
result[0] = i;
result[1] = map.get(complement);
break;
}
}
return result;
}
}


补充:我们最终为了拿到的是下标,所以在map中key选用的是数组中的值,value选用的是数组中每个值对应的下标。此时我们的算法时间复杂度为O(n),我们遍历了两次n个元素,虽然散列表将查找的时间复杂度降为了O(1),但此时的总的时间复杂度为O(n)。

思路3:其实算不上思路三,这个思路和思路二是一样的,但是它在思路二的基础上优化了代码,我们原本需要两次循环才能完成的任务其实在一次循环中即可完成。试想,在一次循环中我们直接检测当前的map中是否含有当前元素的补码,如果存在那就说明我们找见了这两个数,只需输出各自的下标即可;否则,我们需要我们就把当前元素放到map中。如此一来一次循环即可完成任务。

实现代码:

class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0;i<nums.length;i++){
int complement = target-nums[i];
if(map.containsKey(complement)){
result[0] = map.get(complement);
result[1] = i;
}
map.put(nums[i], i);
}
return result;
}
}


对比:下图的runtime由下到上是对应的这三个解决办法,结果不言而喻。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: