文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書
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].
2. 求解
解法一
這個題最簡單也是最容易的就是兩層循環遍歷,這個沒什么可說的,時間復雜度為O(n^2)。
public class Solution {
public int[] twoSum(int[] nums, int target) {
int result[] = new int[2];
int n = nums.length;
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
int sum = nums[i] + nums[j];
if(sum == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return result;
}
}
Leetcode Accepted,Runtime: 45 ms。
解法二
思考一下,如何進行優化呢?首先,條件為nums[i] + nums[j] = target
,已知target和nums[i]的情況下,能不能直接確定nums[j]在數組中是否存在呢?這是可以的,很容易想到map結構,當然數據結構要變換一下,而map的查詢復雜度為O(1),map結構的設計有兩種,要不是key為整數,要不key為整數的索引。由于我們求的是整數的索引,因此應該將key設為整數,value為整數的索引。但key為整數有一個問題就是,如果數組中存在相同整數,則后一個放入的數值會覆蓋前一個,因此需要單獨處理。題目中明確說了一個輸入只有一個解,因此如果出現兩個整數相等的情況,只需要找到另一個數字的索引即可。
public class Solution {
public int[] twoSum(int[] nums, int target) {
int result[] = new int[2];
int n = nums.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++) {
int other = target - nums[i];
map.put(nums[i], i);
if(map.containsKey(other)) {
//兩個數字不等情況
if(other != nums[i]) {
//注意順序
result[0] = map.get(other);
result[1] = i;
break;
}else {
//數字相等情況
result[0] = i;
for(int j = i + 1; j < n; j++) {
if(nums[j] == other) {
result[1] = j;
return result;
}
}
}
}
}
return result;
}
}
Leetcode Accepted,Runtime: 12 ms。