码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] 12. Merge Sorted Array

时间:2014-11-20 23:30:29      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:io   ar   使用   sp   for   strong   on   art   问题   

这道题的无聊之处在于题目其实给了一些很奇怪的测试用例。比如他会给一些空的数组来,但是这个是不科学的,因为在C++中不允许定义一个空的列表,我们用的又不是那种糙又快的python,所以在这里我遇到了一些问题,后来还是解决了。这道题题目如下:

Given two sorted integer arrays A and B, merge B into A as one sorted array.

Note:

You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.

然后这个地方给A的长度又非常的蛋疼,又是m指A的长度,又是A的长度无限大,这让一个严格静态的C++使用者非常蛋疼。当然也有可能是我水平不行【逃!

我一开始是想到我先把B做成有序,然后每次给A做个插入就行了,时间消耗那里在B有序后只用遍历A一次了,(但是每次移位置还是要有消耗,这个我没算出来),这个在遇到题目上的那些奇怪测试与奇怪的A的长度上出了各种问题。所以我干脆直接定义了一个vector,然后把B排序,然后将两个数组合并,这个算法也是算导的第一章内容。代码如下:

void Qsort(int a[], int low, int high)
{
	if (low >= high)
	{
		return;
	}
	int first = low;
	int last = high;
	int key = a[first];/*用字表的第一个记录作为枢轴*/
	while (first<last)
	{
		while (first<last&&a[last] >= key)
			--last;
		a[first] = a[last];/*将比第一个小的移到低端*/
		while (first<last&&a[first] <= key)
			++first;
		a[last] = a[first];/*将比第一个大的移到高端*/
	}
	a[first] = key;/*枢轴记录到位*/
	Qsort(a, low, first - 1);
	Qsort(a, first + 1, high);
}

void main()
{
	
	int A[] = { 1, 2, 3, 4, 6, 7, 14, 15, 20, 35, 45, 55, 56, 57, 58 };
	int B[] = { 9, 5, 38 };
	int m = sizeof(A) / sizeof(A[0]);
	int n = sizeof(B) / sizeof(B[0]);
	int i = 0;
	int j = 0;
	vector<int> tmp;

	Qsort(B, 0, n - 1);
	i = 0;
	j = 0;
	while (i < m && j < n)
	{
		if (A[i] > B[j])
		{
			tmp.push_back(B[j]);
			j++;
		}
		else
		{
			tmp.push_back(A[i]);
			i++;
		}
	}

	while (i < m)
	{
		tmp.push_back(A[i]);
		i++;
	}
	while (j < n)
	{
		tmp.push_back(B[j]);
		j++;
	}
	
	for (i = 0; i < m+n; i++)
	{
		cout << tmp.at(i) << ‘ ‘;
	}


	system("PAUSE");
}

 

然后直接通过了。

[leetcode] 12. Merge Sorted Array

标签:io   ar   使用   sp   for   strong   on   art   问题   

原文地址:http://www.cnblogs.com/TinyBox/p/4111752.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!