入职一年,还是菜的一笔,真的是对不起程序员这个工作,坚持刷leetcode,每天至少一题,在此记录,给自己一个交代。
题目:
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.
给你int数组nums[]和一个int值target,输出nums中两个相加等于target的坐标。
例子:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
方法一(自己想到的):
for(int i = 0; i<nums.length;i++){
for(int k = i + 1; k<nums.length;k++) {
if((nums[i] + nums[k]) == target) {
return new int[] {i, k};
}
}
}</pre><p></p><pre>优点:思路简单,直观;
缺点:时间复杂度是O(n2)
方法二(hashMap):
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) };
}
}优点:时间复杂度是O(n),先把数据方到HashMap中,后面遍历是只需要去HashMap中比较;方法三(hashMap进阶版):
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);
}优点:只需要遍历一遍数组,时间复杂度也是O(n);
本文针对LeetCode上的经典题目“两数之和”提供了三种不同的解决方案,包括双层循环、使用HashMap的两种不同方式,详细分析了每种方法的时间复杂度。
&spm=1001.2101.3001.5002&articleId=51817255&d=1&t=3&u=943bbf31165d4c4c845974f1866d2d35)
502

被折叠的 条评论
为什么被折叠?



