題目
leetcode-1
難度:簡單
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:暴力法
在leetcode中運行用時: 65 ms, 在Two Sum的Java提交中擊敗了19.51% 的用戶
複雜度分析:
時間複雜度:O(n^2)
空間複雜度:O(1)。
解法思路:按大神的推薦,任何一道算法題,都有對應的暴力解法。當實在想不出其他方法時,暴力法就是你的選擇。
public int[] twoSum1(int[] nums, int target) {
int length = nums.length;
for (int i = 0; i < length; ++ i)
for (int j = i + 1; j < length; ++ j)
if (nums[i] + nums[j] == target)
return new int[]{i,j};
return null;
}
解法2:兩遍哈希表
在leetcode中執行用時: 11 ms, 在Two Sum的Java提交中擊敗了74.59% 的用戶
複雜度分析:
時間複雜度:O(n)
空間複雜度:O(n)。
解題思路:以空間換時間
public int[] twoSum2(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
解法3:一遍哈希表
在leetcode中執行用時: 4 ms, 在Two Sum的Java提交中擊敗了99.61% 的用戶
複雜度分析:
時間複雜度:O(n)
空間複雜度:O(n)。
解題思路:所求的兩個值,一旦有一個已經在哈希表中,那麼另一個值便可在數組遍歷過程中找出
public int[] twoSum3(int[] nums, int target) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
int[] res = new int[2];
for (int i = 0; i < nums.length; ++i) {
if (m.containsKey(target - nums[i])) {
res[0] = i;
res[1] = m.get(target - nums[i]);
break;
}
m.put(nums[i], i);
}
return res;
}
文章結束。