leetcode.hash相关.q1_两数之和

大四了,计算机专业要去找工作。听说一般公司笔试环节题目是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底层有一定了解,一遍要对匹配优化有一定了解,要减少重复不必要的匹配。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值