難度:簡單
題目:
給定一個整數(shù)數(shù)組 nums?和一個目標(biāo)值 target,請你在該數(shù)組中找出和為目標(biāo)值的那?兩個?整數(shù),并返回他們的數(shù)組下標(biāo)。
你可以假設(shè)每種輸入只會對應(yīng)一個答案。但是,數(shù)組中同一個元素不能使用兩遍。
來源:力扣(LeetCode)
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
public int[] twoSum(int[] nums, int target) {
? ? ? ? int[] answers = new int[2];
? ? ? ? int sum =0;
? ? ? ? for(int i=0;i<nums.length;i++) {
? ? ? ? for(int j=i+1;j<nums.length;j++) {
? ? ? ? sum = nums[i]+nums[j];
? ? ? ? if(sum == target) {
? ? ? ? answers[0] = i;
? ? ? ? answers[1] = j;
? ? ? ? break;
? ? ? ? }
? ? ? ? }
? ? ? ? }
? ? ? ? return answers;
}
暴力法破解,用時95ms 內(nèi)存消耗40.1MB,十分耗費資源。
官方提供的兩邊哈希表的方法
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);
????????}
????????for?(int?i?=?0;?i?<?nums.length;?i++)?{
????????????int?complement?=?target?-?nums[i];
????????????if?(map.containsKey(complement)?&&?map.get(complement)?!=?i)?{
????????????????return?new?int[]?{?i,?map.get(complement)?};
????????????}
????????}
????????throw?new?IllegalArgumentException("No?two?sum?solution");
????}
用時3ms 內(nèi)存消耗40.1MB 提高了查詢效率,但還是耗費資源空間。