兩數之和
一、要求
給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9 因爲 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
二、思路
這道題挺簡單的,暴力的話,只要兩層for循環即可,但複雜度是O(N^2)。在使用了HashMap之後,由於HashMap高效的查找效率,可以大大縮減執行時間。有關HashMap的底層原理,可以參考我的另外一篇博客HashMap底層實現原理淺談
三、代碼實現
(1)兩層for循環
public class day1106 {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if ((nums[i] + nums[j]) == target) {
return new int[]{i, j};
}
}
}
return null;
}
(2)使用HashMap
public int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int p = target - nums[i];
if (map.containsKey(p)) {
return new int[]{i, map.get(p)};
}
map.put(nums[i], i);
}
return null;
}