第一種解法:暴力破解
時間複雜度O(n2), 空間複雜度O(1)
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = {0,0};
for(int i = 0; i < nums.length - 1; i++ ){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
}
第二種解法:使用HashMap求解
時間複雜度O(n), 空間複雜度O(1)
思路:在map中使用nums[i],作爲key,使用i作爲value,先用 target - nums[i],查看差值是否存在map中,若不存在,則將當前數值put到map中。
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; ++i){
int value = target - nums[i];
if(map.containsKey(value)){
return new int[] {map.get(value),i};
}
map.put(nums[i], i);
}
return null;
}
}