題目:
給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解題1:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2]; //存放結果的數組
for(int i = 0,len = nums.length;i<len;i++){
for(int j = i+1;j<len;j++){
int k = nums[i]+nums[j]; //循環嵌套相加,判斷結果
if(k==target){
result[0] = i;
result[1] = j;
}
}
}
return result;
}
}
這個是我自己寫的,很簡單的計算,就是嵌套循環,把數據相加,判斷是否等於target。
時間複雜度:O(n^2)
空間複雜度:O(1)
解題2:
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length <= 1) {
return new int[2];
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// key = target - nums[i], just one solution
for (int i = 0; i < nums.length; i++) {
map.put(target - nums[i], i); //先把對應的計算結果存放在一個map中
}
for (int i = 0; i < nums.length; i++) {
Integer v = map.get(nums[i]); //看map當中是否有對應的計算結果
// can't use itself
if (v != null && v != i) {
return new int[] { i, v };
}
}
return null;
}
這是網上看到的另一種解法:首先把數組對應target的結果計算出來
如:nums = [2, 7, 11, 15], target = 9
依此計算出map={7:0,2:1,-2:2,-6:3}; 其中key爲結果,value爲索引
然後再遍歷數組,依次取出,如第一個:nums(0) = 2,所以去map中查看是否有key爲2的結果,
如果查出有對應的結果,說明找到了相加等於target的兩個數,
對應的索引分別是:遍歷的i,map中對應的value值;
時間複雜度:O(n)
空間複雜度:O(n)