**自今日始,开启程序员修炼之路,不可一日之懈怠。leetcode每日刷一道算法题以及每日博客写当日修炼心得。**
今天,刷了第一题,出现了很多粗浅的错误,用惯了IDE,发现自己手写代码没提示的情况下很low,这使我很是羞愧,方法和属性傻傻分不清,数组的长度是属性length而非length();对数组进行循环嵌套遍历时,对index考虑不够周到,很大意的出现了越界错误,警惕之,对一道题的考虑不够全面,实现过于单一,思路狭隘,要加以改进。贴上今日代码,铭记。
class Solution {
public int[] twoSum(int[] nums, int target) {
// return array(nums, target);
// return hashmapTwo(nums, target);
return hashmapOne(nums, target);
}
//笨方法,遍历数组
private int[] array(int[] nums, int target) {
//只有一种解,找到就返回
for (int i = 0; i < nums.length - 1; i ++) {
for (int j = i + 1; j < nums.length; j ++) {
if (target == nums[i] + nums[j])
return new int[]{i,j};
}
}
throw new IllegalArgumentException("No two sum solution");
}
//使用hasMap先存数组元素和对应下标,然后在找到这两个值即可 两遍哈希表
private int[] hashmapTwo(int[] nums, int target){
Map<Integer,Integer> map = new HashMap<>();
//遍历一遍数组nums
for (int i = 0; i < nums.length; i ++)
map.put(nums[i], i);
//遍历hasmap找到结果
for (int i = 0; i < nums.length; i ++) {
int temp = target - nums[i];
if (map.keySet().contains(temp) && map.get(temp) != i)
return new int[]{i, map.get(temp)};
}
throw new IllegalArgumentException("No two sum solution");
}
//一遍哈希表
private int[] hashmapOne(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i ++) {
//边存边判断
int temp = target - nums[i];
if (map.keySet().contains(temp))
return new int[]{i,map.get(temp)};
map.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}