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

 

解题过程:

1、分析

   题目的意思是在一个数组中找到两个数,这样的两个数的和等于指定的数,最终返回这样的两个数的下标。

   注意点:

  1. 返回的下标中index1<index2
  2. 下标不是从0开始的;
  3. 并没有说数组是有序的。

2、解题思路

2.1若是有序数组

   对于有序数组,可以通过从两端向中间的方法来进行查找,具体过程如下:

对于数组{2,7,11,15},查找的两个数的和是9,则初始化index1=1index2=length-1=3。此时,分为三种情况:

  1. numbers[index1]+numbers[index2]>target,index2--
  2. numbers[index1]+numbers[index2]<target,index1++
  3. 相等,则返回

程序代码:

/**
	 * 找到两个下标,前提是数组numbers中正好就存在一组这样的解,这种方法只能针对有序表
	 * 
	 * @param numbers数组
	 * @param target目标值
	 * @return返回下标
	 */
	public static int[] twoSum_1(int[] numbers, int target) {
		int result[] = new int[2];// 用于返回最终的下标的数组
		int i = 0;// 第一个下标
		int j = numbers.length - 1;// 第二个下标
		while (i < j) {
			int tmp = numbers[i] + numbers[j];
			if (tmp == target) {
				result[0] = i + 1;
				result[1] = j + 1;
				break;// 跳出循环
			} else if (tmp > target) {
				j--;
			} else {
				i++;
			}
		}
		return result;
	}

时间复杂度为 O(n)。

2.2无序数组

   对于无序数组,要找到两个数的下标,这样的对应关系,比较方便的办法是采用Hash表的存储结构,Hash表中的Key为数组中的值为数组中的值,Hash表中的Value的值为数组的index。在Hash表中key的值是不能重复的,若是数组中有相同的数,则会只保存后一个的value,则不影响问题的求解。

程序代码:

/**
	 * 找到两个下标,前提是数组numbers中正好就存在一组这样的解
	 * 
	 * @param numbers数组
	 * @param target目标值
	 * @return返回下标
	 */
	public static int[] twoSum_2(int[] numbers, int target) {
		int result[] = new int[2];// 用于返回最终的下标的数组
		int i = 0;
		int j = 0;
		HashMap<Integer, Integer> ht = new HashMap<Integer, Integer>();
		for (int m = 0; m < numbers.length; m++) {
			ht.put(numbers[m], m);
		}
		for (i = 0; i < numbers.length; i++) {
			int tmp = target - numbers[i];
			//存在这样的tmp
			if (ht.containsKey(tmp)) {
				j = ht.get(tmp);
				if (i != j){
					break;
				}else{
					continue;
				}
			}
		}
		//保存好下标
		result[0] = (i<j)?i:j;
		result[1] = i+j-result[0];
		result[0]++;
		result[1]++;
		return result;
	}


时间复杂度为O(n)。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值