LeetCode_1_TwoSum_java

Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.You may assume that eGiven an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


解法一:双层循环  o(n^2)

1.返回条件跳出双层循环 2时间复杂度 3.明天继续优化

//Runtime: 58 ms 2016-8-16 22:06:09
	public static int[] twoSum(int[] nums, int target) {		
		//两次遍历  时间复杂度 n*n  
		int[] result = new int[2];
		int len= nums.length;
		for(int i =0;i<len;i++){
			for(int j=i+1;j<len;j++){
				if(target==nums[i]+nums[j]){
					result[0]=i;
					result[1]=j;	
					return result;
				}
			}
		}
		return result;
	}



-----------------------------------------------------second edit time  2016-8-18 21:05:22-----------------------------------------------------------------------------------

解法二:hash方法   o(n)

            hashmap思路:遍历一次,将数组的值作为map的value,最后要得到的结果是index的值,所以把index值作为value保存。
                         查找map时,查找map中的某个key,时间复杂度为o(1)

2.1 错误解法:

	public static int[] twoSum_Hash_error(int[] nums, int target){
		int[] result = new int[2];
		HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();
		int len=nums.length;
		for(int i=0;i<len;i++){
			map.put(nums[i],i);
		}		
		for(int i=0;i<len;i++){
			if(map.containsKey(target-nums[i])){
				result[1]=i;
				result[0]=map.get(target-nums[i]);
				return result;
			}
		}
		return result;			
	}

错误原因:

1.遍历一次,将所有的值放在map中,再在map中寻找匹配值,错误情况,例如  nums[i]=3 ;target = 6;
2.index 的先后顺序无法确定(index1应该小于index2)

2.2正确hash解法:

	//Runtime: 6 ms    o(n)  空间 o(n)
	public static int[] twoSum_Hash(int[] nums, int target){
		int[] result = new int[2];
		HashMap<Integer, Integer> map= new HashMap<Integer, Integer>();
		int len=nums.length;
		for(int i=0;i<len;i++){
			if(map.containsKey(target-nums[i])){
				result[1]=i;
				result[0]=map.get(target-nums[i]);
				return result;
			}else{
				map.put(nums[i],i);
			}
		}
		return result;			
	}

在一个for循环中,如果target- nums[ i] 不在map中,则存入map中,避免错误1。

同时,当出现匹配情况时,说明后匹配值的index一定在一直map中value对应的index之后,可以避免错误2。

总结:试错和前期脑力输出都是必须的。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值