前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode——Two Sum

LeetCode——Two Sum

作者头像
felixzhao
发布2019-02-13 09:54:50
3050
发布2019-02-13 09:54:50
举报
文章被收录于专栏:null的专栏null的专栏

题目:

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=1,index2=length-1=3。此时,分为三种情况:

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

程序代码:

代码语言:javascript
复制
/**
	 * 找到两个下标,前提是数组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,则不影响问题的求解。

程序代码:

代码语言:javascript
复制
/**
	 * 找到两个下标,前提是数组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)。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年01月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目:
  • 解题过程:
    • 1、分析
      • 2、解题思路
        • 2.1若是有序数组
        • 2.2无序数组
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档