leetcode(1)_two sum

//之前那个博客好像长草很久了于是就重新开一个了

//转行不易,菜鸟还需加倍努力



01 Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

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

Input:numbers={2, 7, 11, 15}, target=9
Output:index1=1, index2=2

---------------------------------------------------------

解1,暴力O(n^2) 

纯暴力93ms通过

加上break可以少18ms

不过时间还是很长

package solution;

public class solution {

	public static int[] twoSum(int[] numbers, int target){
		int[] result=new int[2];
		for(int i=0;i<numbers.length;i++){
			for(int j=i+1;j< numbers.length;j++){
				if (numbers[i]+numbers[j]==target){
					result[0]=i+1;
					result[1]=j+1;
				    break;
				}
			}
		}
		return result;
	}
}

解2,hashmap

6ms通过


HashMap实际上是建立了k(数值)与v(角标)的映射

map.containsKey(key)    //判断key是否存在于map中

map.get(key)  //获得key对应的value

map.put(k,v) // 在map中添加映射


<pre name="code" class="java">public class Solution {

    public int[] twoSum(int[] numbers, int target) {

	HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); //建立HashMap,此时map为空
	int[] result = new int[2];
 
	for (int i = 0; i < numbers.length; i++) {  //利用原始数组进行遍历
		if (map.containsKey(numbers[i])) {
			int index = map.get(numbers[i]);
			result[0] = index+1 ;
			result[1] = i+1;
			break;
		} else {
			map.put(target - numbers[i], i);  //建立的是(target - numbers[i], i)的映射,而非(numbers[i], i)的映射,而且这个映射是不完整的


		}
	}
 
	return result;
    }
}

 

保证了如果存在解,循环到index2的时候一定可以结束

关键是建立合适的映射,类似于把后面的数字挪到前面来了


不过hash表的键只能对应唯一的值,所以如果数组中出现多个相同数值,则不能使用hash

以及还有26%更快的不知道从哪里优化


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值