---
title: "LeetCode[Array] - #1 Two Sum"
author: "Cwind"
date: "2015-07-31T22:25:57Z"
tags: []
categories: ["编程语言"]
slug: "leetcode-array-1-two-sum"
draft: false
lastmod: "2015-07-31T22:26:53Z"
id: 2232051
url: "https://cwind.iteye.com/blog/2232051"
---

原题链接：[#1 Two Sum](https://leetcode.com/problems/two-sum/)

 

**要求：**

给定一个整数数组，找出其中的两个数，使之相加能够得到目标数字。

函数twoSum应当返回这两个数的索引，index1应小于index2。请注意，这两个索引并非从零开始计数。

假定每个输入都有且只有一个解。

 

例：

输入：numbers{2, 7, 11, 15}, target=9

输出：index1=1, index2=2

 

**难度：**中等

 

**分析：**

对于这个问题，很直白的一个解是如方案1的一个双重循环。由于有且只有一个解，只要遍历时发现两个元素相加为目标值，便跳出循环并将这两个元素的索引返回即可。此方案最坏情况下的时间复杂度为O(n2)。

解决方案2使用一个HashMap作为辅助数据结构，建立倒排索引，将数组中的每个元素值作为key，该元素的索引作为值加入HashMap。然后遍历一次数组，对于数组中的每一项nums\[i]，当发现target-nums\[i]也在HashMap的键集中，将对应项的索引返回即可。

方案2的唯一问题是原数组中可能有多个不同索引对应的值相同，此时加入HashMap时后加入的会将之前的值覆盖。故返回结果时需要注意这种情况，符合条件时将较小的索引值直接返回，而不是从反向索引中取值。

 

**解决方案：**

方案1：

 

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

 

 

方案2:

```
    public int[] twoSum2(int[] nums, int target) {
        Map map = new HashMap<Integer, Integer>();
        for(int i=0; i<nums.length; i++){
            map.put(nums[i], i+1);
        }

        for(int i=1; i<=nums.length; i++){
            if(map.containsKey(target-nums[i-1])&&((Integer)map.get(target-nums[i-1])>i)){
                return new int[] {i, (Integer)map.get(target-nums[i-1])};
            }
        }

        return new int[0];
    }
```

 [简单测试程序](https://github.com/cwind001/LeetCode/blob/master/LeetCodeJava/src/main/java/com/cwind/leetcode/array/TwoSum.java)