您的位置:首页 > 其它

LeetCode----Two Sum

2016-09-14 15:29 399 查看
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


UPDATE (2016/2/13):

The return format had been changed to zero-based indices. Please read the above updated description carefully.

public class Solution {
public int[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int[] result = new int[2];

for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(numbers[i])) {
int index = map.get(numbers[i]);
result[0] = index ;
result[1] = i;
break;
} else {
map.put(target - numbers[i], i);
}
}

return result;
}
}


int* twoSum(int* nums, int numsSize, int target) {
int min = 2147483647;
int i = 0;
for (i = 0; i < numsSize; i++) {
if (nums[i] < min)
min = nums[i];
}
int max = target - min;
int len = max - min + 1;   //确定hash长度
int *table = (int*)malloc(len*sizeof(int));
int *indice = (int*)malloc(2*sizeof(int));
for (i = 0; i < len; i++) {
table[i] = -1;         //hash初值
}
for (i = 0; i < numsSize; i++) {
if (nums[i]-min < len) {
if (table[target-nums[i]-min] != -1) {        //满足相加为target
indice[0] = table[target-nums[i] - min];
indice[1] = i;
return indice;
}
table[nums[i]-min] = i;
}
}
free(table);
return indice;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: