LeetCode 解题报告 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

题意:给定一个数组,还有个数,这个数组中的存在两个数之和正好等于给定的这个数,求这两个数在数组中的下标。

分析:之前遇到过这种类似的题,是求出这两个数,但这次要求出这两个数的下标那么第一种思路就可以想到了

法一:将数组排序,做两个游标,index1,index2,分别指向数组的头和尾,两数之和如果比给定的数大那么index2--,反之index1++,直到两数相等,或者index1>=index2为止。求出了这两个数,然后再和没有排序的数组进行比较,找出所对应的下标就可以了。

这种方法需要复制原始数组,所以空间复杂度为O(n),排序O(nlgn),查找O(n),遍历O(n)所以时间复杂度是O(nlgn)。

法二:不要忘了暴力方法时间复杂度是O(N2)

法三:如果在查找过程中的时间复杂度为O(1)是不是可以更快,使用HashMap可以实现,空间复杂度是O(n),时间复杂度是O(n)


下面先看一下这三种方法中最优解的代码:

public int[] twoSum(int[] numbers, int target) {
		if(numbers.length < 2)
			return null;
		HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
		//存入哈希表中,每个数字对应其下标
		int [] result = new int[2];
		for(int i = 0; i < numbers.length; i++) {
			if(hashMap.containsKey(numbers[i])) {
				int index = hashMap.get(numbers[i]);
				result[0] = index+1;
				result[1] = i+1;
				break;
			}else {
				hashMap.put(target - numbers[i], i);
			}
		}
		return result;
	}

方法一的代码实现:

public int[] twoSum(int[] numbers, int target) {
		int [] numSorted = numbers.clone();
		Arrays.sort(numSorted);
		int index1 = 0, index2 = numSorted.length - 1;
		while(index1 < index2) {
			int sum = numSorted[index1] + numSorted[index2];
			if(sum < target) {
				index1++;
			}
			else if(sum > target) {
				index2--;
			}
			else 
				break;
		}
		int num1 = numSorted[index1];
		int num2 = numSorted[index2];
		index1 = -1;
		index2 = -1;
		for(int i = 0; i< numbers.length; i++) {
			if(num1 == numbers[i] || num2 == numbers[i]) {
				if(index1 == -1) {
					index1 = i+1;
				}
				else
					index2 = i+1;
			}
		}
		int [] result = {index1,index2};
		Arrays.sort(result);
		return result;
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值