标签:style blog class code java tar
这道题看似简单,其实很坑爹啊,动不动就是Time Limit Exceeded, 比如我下面这段TLE的代码,我感觉方法是对的,但是too naive,算法复杂度到了O(N^2),自然就TLE了
而且有一些小语法错误需要注意:for(runner=current+1;;)不能用>;一定所有的case都有return情况,我如果把return写在if语句里,一定要确定不进if语句也要有相应的return情况。
1 public class Solution { 2 public int[] twoSum(int[] numbers, int target) { 3 int[] results=new int[2]; 4 if(numbers==null) return null; 5 for(int current=0; current<numbers.length; current++){ 6 for(int runner=current+1; runner<numbers.length; runner++){ 7 if((numbers[current]+numbers[runner])==target){ 8 results[0]=current+1; 9 results[1]=runner+1; 10 return results; 11 } 12 } 13 } 14 return null; 15 } 16 }
于是想了第二个算法,用Hashtable, 把时间复杂度降低到了O(N)
1 import java.util.*; 2 3 public class Solution { 4 public int[] twoSum(int[] numbers, int target) { 5 int[] results=new int[2]; 6 int smaller, bigger; 7 Hashtable<Integer, Integer> table=new Hashtable<Integer, Integer>(); 8 if(numbers==null) return null; 9 for(int i=0; i<numbers.length; i++){ 10 table.put(numbers[i], i); 11 } 12 for(smaller=0; smaller<numbers.length; smaller++){ 13 int value=target-numbers[smaller]; 14 if(table.containsKey(value)){ 15 bigger=table.get(value); 16 if(smaller>bigger) continue; 17 else if(smaller<bigger){ 18 results[0]=smaller+1; 19 results[1]=bigger+1; 20 return results; 21 } 22 } 23 } 24 return null; 25 } 26 }
贴个别人的solution, 也是用hashmap(未深究)
1 import java.util.*; 2 3 public class TwoSum { 4 public int[] twoSum(int[] numbers, int target) { 5 // Start typing your Java solution below 6 // DO NOT write main() function 7 if (numbers.length == 0) { 8 return null; 9 } 10 Hashtable<Integer, Integer> hash = new Hashtable<Integer, Integer>(); 11 int[] result = new int[2]; 12 int small = 0; 13 int big = 0; 14 for (int i = 0; i < numbers.length; i++) { 15 if (!hash.containsKey(numbers[i])) { 16 hash.put(target - numbers[i], i); 17 } else { 18 small = i < hash.get(numbers[i]) ? i : hash.get(numbers[i]); 19 big = small == i ? hash.get(numbers[i]) : i; 20 21 } 22 } 23 result[0] = small + 1; 24 result[1] = big + 1; 25 return result; 26 27 } 28 }
Leetcode: Two Sum,布布扣,bubuko.com
标签:style blog class code java tar
原文地址:http://www.cnblogs.com/EdwardLiu/p/3710614.html