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.ci
Example:element
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
解決方法:get
①暴力破解,第一層循環給定一個數nums[i],第二層循環查找符合nums[j] == target - nums[i]的值,從第i+1個數開始查找。思路最簡單,用時48msinput
public class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0;i < nums.length ;i ++ ) {
for (int j = i + 1;j < nums.length ;j ++ ) {
if (nums[j] == target - nums[i]) {//使用條件nums[j]+nums[i]==target也能夠
return new int[]{i,j};//注意返回數組的方式
}
}
}
return null;//由於題目給定的情景不會出現這種狀況,因此隨意返回
}
} hash
時間複雜度:O(n^2)由於要雙重循環遍歷值,空間複雜度:O(1)io
②雙向hash表,比較快速的方法是使用HashMap來存放數值及其下標,而後使用map的方法來查找另外一個值。用時11msclass
public 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 ++ ) {
map.put(nums[i],i);
}
for (int i =0;i < nums.length ;i ++ ) {
int sub = target - nums[i];
if(map.containsKey(sub) && map.get(sub) != i){//注意map方法及其返回值。
return new int[]{i,map.get(sub)};
}
}
return null;
}
} 循環
時間複雜度:O(n),由於使用了hash方法查找第二個值。空間複雜度:O(n),新建了hash map。遍歷