2018.10.13學習筆記
阿新 • • 發佈:2018-11-10
10.13學習筆記
今天都在複習這周大學所學的課程,做了一個靜態的簡歷網頁,還挺好看的哈哈。到了晚上才有空坐下來,上了LeetCode刷了一道簡單的演算法題,下面總結下這道演算法題的收穫。
Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
題目簡單意思就是:給定一個數組和一個目標值,找出陣列中兩個數相加之和為目標值的兩個下標,返回一個儲存了兩個下標的陣列,但是不能使用一個相同的元素兩次。
解法1:
public class solution_1 { public int[] twoSum(int[] nums, int target) { for(int i = 0;i<nums.length - 1;i++){ for(int j = i+1;i<nums.length;j++){ if(nums[i] + nums[j] == target){ return new int[]{i,j}; //直接return new int[]{i,j} } } } throw new IllegalArgumentException("no such sum solution");//丟擲一個異常就不會報沒有return語句的錯誤 } public static void main(String args[]){ solution_1 exercise_1 = new solution_1(); int [] sums = {2,7,11,15}; int target = 9; int [] result = exercise_1.twoSum(sums,target); for (int e:result){ System.out.print(e + " "); } } }
這是最容易想到的演算法,演算法的時間複雜度為O(n*n),空間複雜度為O(1)。
解法2:
/* description:trade space for speed 用空間換取時間 two iterations: first is store array to hashMap O(n) = n; */ public class solution_2 { public int[] twoSum(int[] sums, int target) { HashMap<Integer,Integer> sumsMap = new HashMap<>(); for (int i = 0;i<sums.length;i++){ sumsMap.put(sums[i],i); //hashMap 只能通過key獲取value,因此把sum[i]作為key } for (int j = 0;j<sums.length;j++){ int complement = target - sums[j]; if (sumsMap.containsKey(complement) && complement != sums[j]){ return new int[]{j,sumsMap.get(sums[j])}; } } throw new IllegalArgumentException("no such solution"); } }
第二種解法,用空間換取時間,第一次使用iterator將陣列中的職儲存到hashMap中,然後在hashMap中查詢有沒有target—sums[j]的值,由於hashMap是使用雜湊來實現的,所以在hashMap中查詢一個元素的時間複雜度為O(1)。這種演算法的時間複雜度為O(n),空間複雜度也為O(n)。
解法3:
/*
description:use only one iterator to store array into hashMap,and varies to solution_2,solution_3 checked complement in one iterator
*/
public class solution_3 {
public int[] twoSum(int[] sums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
for (int i = 0;i<sums.length;i++){
int complement = target - sums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(sums[i], i);
}
throw new IllegalArgumentException("no such solution");
}
}
第三種解法優化了第二種解法,只使用了一次迭代,雖然與第二種方法的時間複雜度和空間複雜度都相同,但第三種解法明顯優於第二種解法。