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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
大致意思就是給定一個整數數組,找出其中兩個數滿足相加等于指定的目標數字,返回這個兩個數的數組下標。
同時題目還給出了一個隱含的條件:有且只有一個解 —— 數組中的元素不重復
有半年沒刷題了,開始的時候沒有好的思路,先用最笨的方法解決這個問題,二重循環,時間復雜度O(n^2)
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if ((nums[j]) == target - nums[i]) {
result[0] = i;
result[1] = j;
return result;
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
提交通過之后,查看Editorial找到了更好的解法:使用HashMap,由element映射index,遍歷至數組元素element時查找HashMap中是否已存在key等于target - element,若存在即可從HashMap中取出其下標,若不存在則向HashMap中裝入(element, index),這樣只需遍歷數組一次,而在HashMap中的每次查詢時間復雜度均為O(1),所以總的時間復雜度O(n)
import java.util.HashMap;
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result = new int[2];
Map<Integer, Integer> elementToIndex = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (elementToIndex.containsKey(target - nums[i])) {
result[0] = elementToIndex.get(target - nums[i]);
result[1] = i;
return result;
}
elementToIndex.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
以前幾乎沒在LeetCode上刷過題,現在題目總數已經增加到429道了,短時間內是刷不完了,刷題在精不在多,爭取明年暑假之前把一些經典的題目多刷幾遍。另外只用自帶的編輯器寫代碼,堅決不用IDE!