最近準備面試題目,開個新坑慢慢填... ==
題目:
給定一個整數數組和一個目标值,找出數組中和為目标值的兩個數。
你可以假設每個輸入隻對應一種答案,且同樣的元素不能被重複利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
是以傳回 [0, 1]
這道題最簡單的做法就是針對nums裡面的每一個元素,與target求差,然後在nums裡面找有沒有等于這個內插補點的元素。
import java.util.*;
public class TwoSum {
public int[] twoSumBrute(int[] nums, int target) {
int[] result = new int[2];
if (nums == null || nums.length < 2) return null;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == target - nums[j]) {
result[0] = i;
result[1] = j;
}
}
}
return result;
}
}
求解的時間複雜度是O(N^2),效果并不是很好。可以使用哈希表優化,讓尋找內插補點是否在nums中這個操作的時間複雜度從O(N)下降到O(1),整體時間複雜度變為O(N),性能得到極大提升。
import java.util.*;
public class NumAdd1 {
public int[] twoSumHash(int[] nums, int target) {
int [] result = new int[2];
if (nums == null || nums.length < 2) return null;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
result[1] = i;
result[0] = map.get(target - nums[i]);
break;
}
map.put(nums[i], i);
}
return result;
}
}