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

//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]）