給定一個整數(shù)數(shù)組 nums 和一個目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那 兩個 整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,數(shù)組中同一個元素不能使用兩遍。
實(shí)例:
給定 nums = [2, 7, 11, 15], target = 9
因?yàn)?nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
方法一:暴力法
暴力法很簡單,遍歷每個元素x,并查找是否存在一個值與target-x相等的目標(biāo)元素。
class Solution {
// 舉例nums = [2,7,11,15]; target = 9;
public int[] twoSum(int[] nums, int target) {
// 遍歷nums數(shù)組
for (int i = 0; i < nums.length; i++) {
// 再次遍歷數(shù)組nums,初始值為j=i+1
for (int j = i + 1; j < nums.length; j++) {
// 判斷nums[j]+nums[i]=target
if (nums[j] == target - nums[i]) {
// 等式成立直接返回i和j
return new int[] { i, j };
}
}
}
// 等式不成立返回一個沒有結(jié)果
throw new IllegalArgumentException("沒有結(jié)果!");
}
}
方法二:哈希表
class Solution {
// 舉例nums = [2,7,11,15]; target = 9;
public int[] twoSum(int[] nums, int target) {
// 定義一個數(shù)組map,鍵和值都為整數(shù)
Map<Integer, Integer> map = new HashMap<>();
// 遍歷nums數(shù)組
for (int i = 0; i < nums.length; i++) {
// 定義變量complement儲存target - nums[i]的計算結(jié)果
int complement = target - nums[i];
// 判斷map集合里是否有key的值和complement相等
if (map.containsKey(complement)) {
// 有相等的key值,則輸出其key值對應(yīng)的value值和i
return new int[] { map.get(complement), i };
}
// 把nums[i]當(dāng)做map的key值,nums數(shù)組i下班當(dāng)做map的value值
map.put(nums[i], i);
}
// 等式不成立返回一個沒有結(jié)果
throw new IllegalArgumentException("沒有結(jié)果!");
}
}
作者:LeetCode 鏈接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/ 來源:力扣(LeetCode)
浙公網(wǎng)安備 33010602011771號