第三遍提交
<span style="font-weight: bold;"> </span> /** * running time : O(n) */ public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); int size = numbers.length; for(int i=0; i<size; i++){ int curr = numbers[i]; if(!map.containsKey(curr)){ map.put(target - curr, i); }else{ result[0] = map.get(curr) + 1; result[1] = i+1; break; } } return result; }第一遍提交
<strong> </strong> /** * running time is O(n^2) * 返回结果 Time Limit Exceeded * LeetCode使用的测试用例,是超长的数组 * Last executed input: [0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,....] * * 教训: 程序不能只是正确性,还要考虑效率。 */ public int[] twoSumVersion1(int[] numbers, int target) { int[] result = new int[2]; for(int i=0; i<numbers.length; i++){ int rightOperand = target - numbers[i]; for(int j=i+1; j<numbers.length; j++){ if(rightOperand == numbers[j]){ // Please note that your returned answers (both index1 and index2) are not zero-based. result[0] = i+1; result[1] = j+1; return result; } } } return result; }
1. 1st answer is O(n^2)
The two-layer loops algorithm is first idea for most people. However, the running time is O(n^2), which means it might be not be used in real application.
2. 2nd answer based on Hash Map; store all elements on Hash Map.
Disadvantage: This algorithm needs a very big space to store elements in hash map. Most of elements are not the output concerns.
3. 3rd answer based on Hash Map; only store the examined elements on Hash Map.
3.1 the output order is not a matter
3.2 For-loop keeps one output.