題目:
1. 兩數(shù)之和
解法:
解法一: 直接暴力法
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length - 1; i++){
for(int j = i+1; j< nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[]{i, j};
}
}
}
return null;
}
解法二: 遍歷一次數(shù)組即可. 新建一個HashMap, 存儲的key-v結(jié)構(gòu)是(數(shù)組的值 ==> 數(shù)組的下標(biāo)) 然后每次用 target 減去 遍歷的數(shù)組的元素, 判斷HashMap中是否包含該key, 如果包含則返回下標(biāo), 結(jié)束.
public int[] twoSum(int[] nums, int target) {
if((nums == null) || (nums.length < 2)){
return null;
}
Map<Integer , Integer> map = new HashMap<>();
map.put(nums[0], 0);
for(int i=1; i< nums.length; i++){
int tmp = target - nums[i];
if(map.containsKey(tmp)){
return new int[]{map.get(tmp), i};
}else{
map.put(nums[i], i);
}
}
return null;
}