重新开始慢慢总结leetcode之前做过的题,好好写清思路。
Two Sum 是第一题,第一次想到的是暴力枚举的O(N*N) 的方法
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] ret = {0, 0};
if(numbers.length < 2) return ret;
int i = 0;// start from 0
int j = 1; // j is always i+1
while( i < numbers.length) {
j=i+1; //after every j to numbers.length, j should be set to i+1 again
while(j < numbers.length){
if(numbers[i] + numbers[j] == target) break;
j++; // doesn't match, continue
}
i++; // continue
}
if(i<numbers.length && j < numbers.length){
ret[0] = i+1;
ret[1] = j+1;
}
return ret;
}
}
这个方法被leetcode 判断为TLE了,于是需要采用另一种O(N) 或者O(N*logN)的方法,O(N) 可以用HashMap, 也属于暴力解题
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];
//for (int i = 0; i < numbers.length; i++) {
// map.put(target-numbers[i], i);
//}
/*for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) { // check if map countains target - numbers[i]
int index = map.get(target - numbers[i]); // yes, then get the index of target - numbers[i]
result[0] = i+1 ;
result[1] = index+1;
//break;
}
else {map.put(numbers[i], i);} //if not, put numbers[i] at map slot i
}*/
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
int index = map.get(numbers[i]);
result[0] = index+1 ;
result[1] = i+1;
break;
} else {
map.put(target - numbers[i], i);
}
}
return result;
}
被Comment 的for 循环也可以用。