1. 程式人生 > 實用技巧 >C++STL中vector使用策略(二)

C++STL中vector使用策略(二)

下面來看一道LeetCode上的困難題

題目連結:兩個排序陣列的中位數

題解

首先利用 push_back 函式,將 nums2 依次插入到 nums1 尾部,然後利用sort(nums1.begin(),nums2.end())函式將合併後的元素進行排序。最後利用 size() 判斷其元素個數是偶數還是奇數,以此決定輸出中間兩位數的平均數還是中間的數。

程式碼

class Solution {
public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
    {
        for(int its = 0;its < nums2.size();++its)
        {
            nums1.push_back(nums2.at(its));
        }
        sort(nums1.begin(),nums1.end());
        if(nums1.size() % 2 == 0)
        {
            return (double)(nums1.at((nums1.size()/2) - 1) + nums1.at(nums1.size()/2))/2;
        }
        else
        {
            return nums1.at(((nums1.size())/2));
        }
    }
};

列印鋸齒矩陣

鋸齒矩陣是指每一行包含的元素個數不相同的矩陣,比如:
3 5 2 6 1
2 3 4
1 6 2 7

讀入若干對整數(x,y),表示在第 x 行的末尾加上一個元素 y。輸出最終的鋸齒陣列。初始時矩陣為空。

輸入格式

第一行輸入兩個整數 (1≤n,m≤10000),其中 n 表示鋸齒陣列的行數,m 表示插入的元素總數。接下來一共 mm 行,每行兩個整數 x,y(1≤x≤n,0≤y≤10000),表示在第 x 行的末尾插入一個元素 y。

輸出格式

一共輸出 行,每行若干個用空格分隔的整數。如果某行沒有任何元素,則輸出一個空行。

樣例輸入

3 12
1 3
2 2
2 3
2 4
3 1
3 6
1 5
1 2
1 6
3 2
3 7
1 1

樣例輸出

3 5 2 6 1
2 3 4
1 6 2 7

題解

這題剛開始一看可能感覺需要用二維向量vector<vector <int> >vec,但是其實一個vector<int> vec[1000]就能滿足這題的要求了,但是要先分清楚這幾個的區別

vector<vector<int> >vec;//vector裡面每個元素都是vector,相當於二維vector
vector<int>vec[1000];//開一個1000的陣列,裡面每個元素是一個vector
vector<int>vec(1000);//開一個vector,大小1000

程式碼

#include <bits/stdc++.h>
using namespace std;
int main()
{
	vector<int> vec[10005];
	int i,j,n,m,tmp,ans = 0,x,y;
	cin>>n>>m;
	for(i = 0;i < m;i++)
	{
		cin>>x>>y;
		vec[x].push_back(y);
	}		
	for(int i = 1;i <= n;i++)
	{
		for(j = 0;j < vec[i].size();j++)
		{
			if(j != vec[i].size() - 1)
			{
				cout<<vec[i][j]<<" "; 
			}
			else
			{
				cout<<vec[i][j];
			}
		}
		if(i < n)
		{
			cout<<endl;
		}
	}
	return 0;	 
}