每天一道leetCode题--数组--1--两数之和

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数

你可以假设每个输入只对应一种答案,且同样的元素不能被重复使用

示例:

给定nums = [2,7,11,15],target = 9

因为nums[0]+nums[1] = 2 + 7 = 9

所以返回 [0,1]

c代码实现
#include <stdlib.h>

struct object
{
	int val;
	int index;
};

static int compare(const void* a, const void* b)
{
	return ((struct object*)a)->val - ((struct object*)b)->val;
}

static int* twoSum(int* nums, int numSize, int target)
{
	struct object* objs = (struct object*)malloc(numSize*sizeof(object));
	for (int i = 0; i < numSize; ++i)
	{
		struct object& obj = objs[i];
		obj.val = nums[i];
		obj.index = i;
	}

	qsort(objs,numSize,sizeof(*objs),compare); //先排序

	int i = 0;
	int j = numSize - 1;
	int* results = (int*)malloc(2*(sizeof(int)));

	while (i < j)
	{
		int diff = target - objs[i].val;
		if (diff > objs[j].val)
			while (++i < j && objs[i].val == objs[i - 1].val) {}
		else if(diff < objs[j].val)
			while (--j > i && objs[j].val == objs[j + 1].val) {}
		else
		{
			results[0] = objs[i].index;
			results[1] = objs[j].index;
			return results;
		}
	}
	free(objs);
	objs = NULL;
	return NULL;
}

int main()
{
	int arr[] = {3,4,5,6,7};
	int* results = twoSum(arr, sizeof(arr) / sizeof(*arr), 11);
	if (results)
	{
		printf("%d\n", arr[results[0]]);
		printf("%d\n", arr[results[1]]);
		free(results);
		results = NULL;
	}
	else
	{
		printf("not found \n");
	}

	system("pause");
	return 0;
}
c++代码实现
#include <vector>
#include <map>

vector<int> twoSum(int* nums, int numSize, int target)
{
	map<int, int> m;
	vector<int> vec;
	for (int i = 0; i < numSize; ++i)
	{
		map<int, int>::iterator iter = m.find(target - nums[i]);
		if (iter == m.end())
		{
			m[nums[i]] = i;
		}
		else
		{
			vec.push_back(iter->second);
			vec.push_back(i);
			return vec;
		}
	}
	return vec;
}

int main()
{
	int arr[] = {3,4,5,6,7};
	vector<int> results = twoSum(arr, sizeof(arr) / sizeof(*arr), 10);
	if (results.size()> 0)
	{
		printf("%d\n", arr[results[0]]);
		printf("%d\n", arr[results[1]]);
	}
	else
	{
		printf("not found \n");
	}

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值