从今天开始在LeetCode上刷题了,第一题,虽然很简单,但是因为刚刚学习了java,而且代码一直写的都很烂,所以过程还是有点曲折的,值得记录下~
LeedCode原题:
Two Sum
看到题目以后,想法是使用数组进行双重循环好了,所以编写代码如下:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] result = new int[2];
for(int i = 0;i<len-1;i++){
for(int j = i+1 ;j<len;j++)
if(nums[i] + nums[j] == target)
{
result[0] = i;
result[1] = j;
break;
}
}
return result;
}
}
调试运行竟然顺利Finished!不禁想要欢呼~
但是还是觉得这么写有点low,于是在网上查询了其他的方法,惊奇的发现,有的人使用双重循环,因为时间复杂度没有通过,不知道为什么我的成功了~
而参看有人提出的使用hashmap,将数值作为key,索引值作为value,代码如下:
public class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
Map<Integer,Integer> map = new HashMap();
for(int i=0;i<len;i++)
{
map.put(nums[i],i);//nums的值传入HashMap
if (map.containsKey(target - nums[i])) {
int n = map.get(target - nums[i]);
if(n<i)//题目规定同一个数据不能使用两次
return new int[]{map.get(target - nums[i]), i};
}
}
return new int[]{-1, -1};
}
}
好长时间没有刷leetcode了,最近又重新捡起来,因为要找工作啊啊啊啊啊,但是最基本的都还是会搞错,不过不要灰心,多练习一定可以的。
上面的第二种解法是4月份的时候刷题记录下来的,都不记得当时是否有真的运行过,这次重新看过这道最简单的题目,搞了半天才发现是错误的,因为hashmap中的key值是不能重复的,如果有重复的key,则value会被覆盖,所以例如nums = {3,3},那么hashmap的size最终只能是1个,但是该题目中数不能重复利用,所以是error!
改进,基本思路还是不变,但是首先先要判断target-nums[i]是否在hashmap中有key值,如果没有再存入到hashmap中,这样相当于是在nums[0]到nums[i-1]的hashmap中找符合条件的target-nums[i]。
代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int len = nums.length;
int[] re = new int[2];
for(int i=0;i<len;i++){
int tmp = target - nums[i];
if(map.containsKey(tmp))
{
re[0] = map.get(tmp);
re[1] = i;
}
map.put(nums[i],i);// 最关键的是这条语句的位置
}
return re;
}
}