我的方法:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] targets = new int[2];
for(int i = 0;i < nums.length;i++){
for(int j = i + 1;j < nums.length;j++){
if(nums[i] + nums[j] == target){
targets[0] = i;
targets[1] = j;
}
}
}
return targets;
}
}
小结:此方法位暴力遍历法
时间复杂度O(n^2)
空间复杂度O(1)
第二种
哈希法
我们需要找出它的索引。保持数组中的每个元素与其索引相互对应的最好方法是什么?哈希表。
通过以空间换取速度的方式,我们可以将查找时间从 O(n)O(n) 降低到 O(1)O(1)。哈希表正是为此目的而构建的,它支持以 近似 恒定的时间进行快速查找。我用“近似”来描述,是因为一旦出现冲突,查找用时可能会退化到 O(n)O(n)。但只要你仔细地挑选哈希函数,在哈希表中进行查找的用时应当被摊销为 O(1)O(1)。
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
时间复杂度:O(n)
空间复杂度:O(n) 哈希表存储的元素个数