하루 leetCode 질문 - 두 숫자 및 배열 --1489--

정수 및 타겟 값의 어레이 감안하여 다수 개의 목표로 배열 식별

각 입력에 해당하는 하나의 답을 가정 할 수 있으며, 같은 요소는 재사용 할 수 없습니다

예 :

주어 nums = [2,7,11,15] 목표 = 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 개 원래 기사 · 원 찬양 한 · 전망 2302

추천

출처blog.csdn.net/lpl312905509/article/details/104032808