从现在开始为了巩固思路,每刷一题都会或多或少记录自己的思路。
希望以此能够督促自己的ACM刷题之路。
现在是跟着闫学灿的暑期leetcode打卡,已经打了第七周,这周是基本数据结构专题,从第一题开始。
/***********************
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**************************/
方法一: 暴力
思路很简单,以此遍历是否相加等于目标值。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
res[0] = -1;
res[1] = -1;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
res[0] = i;
res[1] = j;
return res;
}
}
}
return res;
}
}
时间复杂度 O(n^2)
方法二:哈希表优化
来源于Leetcode官方题解对于哈希表的优化描述:
通过以空间换取速度的方式,我们可以将查找时间从 O(n)O(n) 降低到 O(1)O(1)。哈希表正是为此目的而构建的,它支持以 近似 恒定的时间进行快速查找。我用“近似”来描述,是因为一旦出现冲突,查找用时可能会退化到 O(n)O(n)。但只要你仔细地挑选哈希函数,在哈希表中进行查找的用时应当被摊销为 O(1)O(1)。
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
–思路也很简单,就是每次访问数组元素时在哈希表中查找是否有值匹配target - nums[i] , 有就是答案,没有就将nums[i]加入到哈希表中。
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
return new int[]{-1, -1};
}
时间复杂度 O(n)
第一次写博客,有需要改正的地方请指教。