twoSum

这几天开始学习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;
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值