首页 > ACM题库 > LeetCode > LeetCode-Two Sum[数组]
2014
11-18

LeetCode-Two Sum[数组]

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

标签: Array Hash Table
分析

方法1:暴力,复杂度$O(n^2)$,会超时

方法2:hash。用一个哈希表,存储每个数对应的下标,复杂度$O(n)$.

方法3:先排序,然后左右夹逼,排序$O(n\log n)$,左右夹逼$O(n)$,最终$O(n\log n)$。但是注意,这题需要返回的是下标,而不是数字本身,因此这个方法行不通。

代码1

//LeetCode, Two Sum
// 方法2:hash。用一个哈希表,存储每个数对应的下标
// 时间复杂度O(n),空间复杂度O(n)
class Solution {
public:
    vector<int> twoSum(vector<int> &num, int target) {
        unordered_map<int, int> mapping;
        vector<int> result;
        for (int i = 0; i < num.size(); i++) {
            mapping[num[i]] = i;
        }
        for (int i = 0; i < num.size(); i++) {
            const int gap = target - num[i];
            if (mapping.find(gap) != mapping.end() && mapping[gap] > i) {
                result.push_back(i + 1);
                result.push_back(mapping[gap] + 1);
                break;
            }
        }
        return result;
    }
};

Java代码:

public class Solution {
    static class Node implements Comparable<Node>{
        int val,index;
        public Node(int v,int i){
            val = v;
            index = i;
        }
        @Override
        public int compareTo(Node o) {
            return this.val - o.val;
        }
    }

    public int[] twoSum(int[] numbers, int target) {
        int[] xy = new int[2];
        Node[] nodes = new Node[numbers.length];
        for(int i=0; i<nodes.length; i++){
            nodes[i] = new Node(numbers[i], i+1);
        }
        Arrays.sort(nodes);
        int i = 0, j=numbers.length-1;
        while(i < j){
            if(nodes[i].val + nodes[j].val == target){
                break;
            }else if(nodes[i].val + nodes[j].val < target){
                i++;
            }else{
                j--;
            }
        }
        xy[0] = nodes[i].index;
        xy[1] = nodes[j].index;
        Arrays.sort(xy);
        return xy;
    }
}

  1. 有一点问题。。后面动态规划的程序中
    int dp[n+1][W+1];
    会报错 提示表达式必须含有常量值。该怎么修改呢。。

  2. 为什么for循环找到的i一定是素数叻,而且约数定理说的是n=p1^a1*p2^a2*p3^a3*…*pk^ak,而你每次取余都用的是原来的m,也就是n

  3. L(X [0 .. M-1],Y [0 .. N-1])= 1 + L(X [0 .. M-2],Y [0 .. N-1])这个地方也也有笔误
    应改为L(X [0 .. M-1],Y [0 .. N-1])= 1 + L(X [0 .. M-2],Y [0 .. N-2])