LeetCode No2--Two Sum

来源:互联网 发布:c语言中文版下载 编辑:程序博客网 时间:2024/04/29 23:32

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

void mysort(int *nums,int numsSize,int *index){    int i,j;    int x,ind;    for (i = 0;i<numsSize;i++)index[i] = i+1;    for(i=1;i<numsSize;i++)    {        if(nums[i]<nums[i-1])        {            j = i-1;            x = nums[i];            ind = index[i];            nums[i] = nums[i-1];            index[i] = index[i-1];            while(x <nums[j])            {                nums[j+1] = nums[j];                index[j+1] = index[j];                j--;            }            nums[j+1]=x;            index[j+1] = ind;        }    }}int *twoSum(int* nums, int numsSize, int target) {    //先排序int *index;int i;index = (int *)malloc(sizeof(int)*numsSize);mysort(nums,numsSize,index);int *p,*q;p = nums;q = nums + numsSize-1;int *result = (int *)malloc(2*sizeof(int));int *ind1 = index;int *ind2 = index + numsSize-1;result[0] = *ind1;result[1] = *ind2;while(p<=q){    if(*p + *q==target)    {//return result;        break;    }    else if(*p + *q>target)    {        q--;         ind2--;            }    else    {       p++;       ind1++;    }}result[0] = *ind1;result[1] = *ind2;int *index_result = (int *)malloc(2*sizeof(int));mysort(result,2,index_result);return result;free(result);    }void main(){int nums[] = {-1,-2,-3,-4,-5};int numsSize = 5;int target = -8;int *result = new int[2] ;result = twoSum(nums, numsSize, target);printf("%d %d\n",result[0],result[1]);delete []result;getchar();}

我的想法有两个:

1. 先排序再用两个指针完成

2.hashmap

对于第一种想法,先用最慢的直接插入(这里可以用其他快的排序算法)排序,然后再处理,可是上传到leetcode中提示输入[-1,-2,-3,-4,-5]target=-8时错误,可是同样的输入在vs2010上运行是正确的啊 不知道哪里错了哎 以后发现错的地方就更新 

hashmap版本:

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        unordered_map<int, int> map;        int n = (int)nums.size();        for (int i = 0; i < n; i++) {            auto p = map.find(target-nums[i]);            if (p!=map.end()) {                return {p->second+1, i+1};            }            map[nums[i]]=i;        }}};


0 0
原创粉丝点击