刷题笔记
1.Two Sum
题目
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
思路
- 两层循环判断两数加和是否等于target即可。
代码实现
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
int[] ans = new int[2];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == target) {
ans[0] = i;
ans[1] = j;
return ans;
} else {
continue;
}
}
}
return ans;
}
}
这种解法速度很快,占用内存较多:
再来看只需要遍历一遍数组的方法:
class Solution {
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; map.put(numbers[i], i++))
if (map.containsKey(target - numbers[i]))
return new int[]{map.get(target - numbers[i]),i};
return new int[]{0,0};
}
}
这种解法保证只用遍历一遍数组,解法思路如下:
- 首先创建一个hashmap,键值对的类型都是interger。
- 然后对数组进行遍历,精巧的地方在于,在遍历最开始的时候,hashmap是空的,相当于循环只是在往hashmap中放入键值对,而判断语句判断target-numbers[i]这个键在map中存不存在,如果存在则说明匹配成功,则可以反悔两个下标;匹配不成功则继续循环放入键值对。
- 这种方法的运行结果很成功,改善了占用空间的问题。