LeetCode No2--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

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;
        }
}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值