題目描述:
給定一個整數數組 nums
和一個目標值 target
,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
/*
方法一:暴力搜索法:時間複雜度O(n2)
class Solution {
public int[] twoSum(int[] nums, int target) {
if(nums == null || nums.length<1) return null;
for(int i=0; i<nums.length;i++){
for(int j= nums.length-1;j>i;j--){
if(nums[j]+nums[i]== target){
return new int[]{i,j};
}
}
}
return null;
}
}
*/
/*
方法二:
哈希:時間複雜度O(1)
class Solution{
public int[] twoSum(int[] nums, int target){
if(nums == null || nums.length < 1) return null;
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0; i<nums.length;i++ ){
if(map.containsKey(target-nums[i])){
return new int[]{map.get(target-nums[i]),i};
}
map.put(nums[i],i);
}
return null;
}
}
*/