无意间在优快云博客上逛时看到了leetcode这个好东西。leetcode是一个再线提交代码的东西,重要的是里面的题目大部分都是各IT大公司笔试时的常考题。博主果断决定有空时做做里面的题了,并与大家分享
原题地址:https://oj.leetcode.com/problems/two-sum/
这个题看似简单,相信几乎所有人也都能写出来,但问题是效率!很多人都能想到一对一对的比较,但这样的时间复杂度为O(n^2)。下面就是很多人能想到的代码,我最开始也是想到的下面的方法。
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
for(int i=0;i<numbers.length;i++) {
for(int j=i+1;j<numbers.length;j++) {
check = numbers[i] + numbers[j];
if(check == target){
result[0] = i+1;
result[1] = j+1;
return result;
}
}
}
return null;
}
}
写完一提交,judge的结果是Time exceeded!! 时间复杂度太高了!这里就得表扬leetcode了,leetcode比较好的地方就在它不仅会检测你代码的正确性,它还会检测你代码的执行效率。
提交没有被accept,只有接着尝试其他方法,在论坛里看了看才知道大牛们们都是用Hash表来优化的。使用哈希表,时间复杂度为O(n),同时空间复杂度也是O(n)。下面是使用Hash表来解决时的代码:
public class Solution{
public int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (hashMap.containsKey(target - numbers[i])) {
result[1] = i + 1;
result[0] = hashMap.get(target - numbers[i]);
return result;
}
hashMap.put(numbers[i], i + 1);
}
return result;
}
}
本文为原创,转载请注明转载自:http://blog.youkuaiyun.com/computerme/article/details/40396395