大四了,计算机专业要去找工作。听说一般公司笔试环节题目是leetcode中等题目难度,这块记录下我这段时间leetcode的刷题的经历包括思路过程和代码。刷题路径先从一些考得频率比较高的题目开始。
题目: leetcode.q1_两数之和
解法一:暴力算法
思路: 双重循环遍历数组,遍历过程中判断是否是同一元素,是,跳过。如果不是,判断元素之和是否和目标数值相同,相同就跳出循环。用一个数组记录结果,并返回。
代码:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] result= new int[2];
for(int i = 0; i < nums.length; i++) {
for(int j = 0; j < nums.length; j++) {
if(i == j)continue;
if(nums[i] + nums[j] == target) {
result[1] = i;
result[0] = j;
break;
}
}
}
return result;
}
}
分析: 时间复杂度O(n^2),空间复杂度O(1)。
结果: 能水过,hhh。
解法二:两遍hashmap优化
思路: 将数组中所有元素放入hashmap中。再遍历数组。在hashmap中判断是否存在根据目标值和数组元素值之差的值,并且判断不能为同一元素。如果存在存入int数组返回。
代码:
public class Solution_hash {
public int[] twoSum(int[] nums, int target) {
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 comp = target - nums[i];
if(map.containsKey(comp) && map.get(comp) != i) {
return new int[] {i,map.get(comp)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
分析: 利用了hashmap查询据复杂度O(1)的特性,减小了暴力匹配第二层循环的工作量。时间复杂度降到了O(n)。由于hashmap的建立空间复杂度升到了O(n),这也是一种空间换时间的策略。
结果: 通过,在时间上有了优化。
解法三:一遍hashmap
思路: 将放入元素和判断hashmap中是否存在对应的值封装在一次遍历数组中,减去了重复匹配的次数。
代码:
public class Solution_hashmap1 {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap();
for(int i = 0 ; i < nums.length; i++) {
int comp = target - nums[i];
if(map.containsKey(comp)) {
return new int[] {i,map.get(comp)};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
分析: 空间复杂度最多是O(n),也减少了hash冲突。
结果: 通过,进一步优化
总结
两遍hashmap优化的话要对hashmap底层有一定了解,一遍要对匹配优化有一定了解,要减少重复不必要的匹配。