題目
//給定一個整數(shù)數(shù)組 nums 和一個整數(shù)目標值 target,請你在該數(shù)組中找出 和為目標值 target 的那 兩個 整數(shù),并返回它們的數(shù)組下標。
//
// 你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,數(shù)組中同一個元素在答案里不能重復(fù)出現(xiàn)。
//
// 你可以按任意順序返回答案。
//
//
//
// 示例 1:
//
//
//輸入:nums = [2,7,11,15], target = 9
//輸出:[0,1]
//解釋:因為 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
//
//
// 示例 2:
//
//
//輸入:nums = [3,2,4], target = 6
//輸出:[1,2]
//
//
// 示例 3:
//
//
//輸入:nums = [3,3], target = 6
//輸出:[0,1]
//
//
//
//
// 提示:
//
//
// 2 <= nums.length <= 104
// -109 <= nums[i] <= 109
// -109 <= target <= 109
// 只會存在一個有效答案
//
//
//
//
// 進階:你可以想出一個時間復(fù)雜度小于 O(n2) 的算法嗎?
// Related Topics 數(shù)組 哈希表
// ?? 17130 ?? 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] twoSum(int[] nums, int target) {
}
}
//leetcode submit region end(Prohibit modification and deletion)
思路
- 用HashMap把值、下標存儲起來,方便查找
- 判斷HashMap中是否有 (target-當(dāng)前值)
實現(xiàn)
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for (int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
int[] res = new int[2];
for (int i=0;i<nums.length;i++){
int temp = target - nums[i];
//判斷是否存在,并且不能是同一個數(shù)據(jù)
if (map.containsKey(temp) && map.get(temp)!=i){
res[0] = i;
res[1] = map.get(temp);
}
}
return res;
}
結(jié)果
info
解答成功:
執(zhí)行耗時:5 ms,擊敗了48.61% 的Java用戶
內(nèi)存消耗:42.4 MB,擊敗了28.75% 的Java用戶
思路
遍歷了兩次,這里能不能優(yōu)化一下呢?
優(yōu)化
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
int[] res = new int[2];
for (int i=0;i<nums.length;i++){
if (map.containsKey(target-nums[i])){
res[0] = map.get(target-nums[i]);
res[1] = i;
return res;
}
map.put(nums[i],i);
}
return res;
}
結(jié)果
info
解答成功:
執(zhí)行耗時:1 ms,擊敗了98.28% 的Java用戶
內(nèi)存消耗:42.6 MB,擊敗了18.89% 的Java用戶