这几天开始学习java,于是开始刷题,选择了leetcode,发现自己好久没有码代码了,手感和灵感少了不少,几乎就是小白,今天做的第一道题,Two Sum
这道题的题目是这样的,题目给出一组数和一个目标数字,在已知的数中找出两个相加可得目标数字的数字,并且返回两个数的下标。
在最开始我是开始找答案,参考别人的,写出了三种答案:
1.是最暴力的,时间复杂度是最差的O(N2)代码如下:
class Solution{
public int[] twoSum(int[] nums,int target){
int[] index = new int[]{0,1};
for(int i = 0 ;i < nums.length; i++){
for(int j = i + 1;j < nums.length;j++){
if(target == nums[i] + nums[j]){
index[0] = i;
index[1] = j;
return index;
}
}
}
return index;
}
}
2.第二种方法是使用HashSet来辅助,时间复杂度变得简单了O(N)代码如下:
class Solution{
public int[] twoSum(int[] nums,int target){
int[] index = new int[]{0,1};
Set hashset = new HashSet();
for( int i = 0; i < nums.length; i++){
if(hashset.add(target - nums[i])){
hashset.remove(target - nums[i]);
hashset.add(nums[i]);
}
else{
index[1] = i;
index[0] = hashset.get(target - nums[i]);
return index;
}
return index;
}
return index;
}
}
3.第三种方法就是使用Hashmap,和第二种方法是差不多的
class Solution{
public int[] twoSum(int[] nums,int target){
int[] index = new int[]{0,1};
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
for(int i = 0;i < nums.length;i++){
if(hm.containsKey(target-nums[i])){
index[1] = i;
index[0] = hm.get(target-nums[i]);
return index;
}else{
hm.put(nums[i], i);
}
}
return index;
}
}