每天一道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;
}
发布了43 篇原创文章 · 获赞 1 · 访问量 2302

猜你喜欢

转载自blog.csdn.net/lpl312905509/article/details/104032808