啊哈!演算法 案例用c++實現
阿新 • • 發佈:2020-12-23
技術標籤:c++
第二章
題目2.1:
思路:
題目其實已經給出思路了
程式碼
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution {
public:
vector<int> deCode(vector<int>& nums) {
vector<int> ret_v;
queue<int> qu;
for (int i=0;i<nums.size() ;i++)
{
qu.push(nums[i]);
}
while (!qu.empty())
{
//將刪除的元素放到 ret中
ret_v.push_back(qu.front());
qu.pop();
if (!qu.empty())
{
// 然後將元素放到佇列的尾端
int front = qu.front();
qu.pop();
qu.push(front);
}
}
return ret_v;
}
};
int main()
{
vector<int> nums{ 6,3 ,1,7,5,8,9,2,4 };
Solution s;
vector<int> ret_v=s.deCode(nums);
for (auto one: ret_v)
{
cout << one << " ";
}
}
題目2.2
思路:
桌子上面的牌用vector儲存
哼哈二將手中的牌用 佇列儲存就可以了。
程式碼:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class Solution {
private:
void doLoad(vector<int> &restore, queue<int> &qu)
{
int front = qu.front();
qu.pop();
auto it = find(restore.begin(), restore.end(), front);
if (it != restore.end())
{
vector<int> append_v;
//需要彈出 將其補到restore的尾端
int j = int(restore.size()) - 1;//避免無符號轉換
while (j >= 0 && restore[j] != front)//這裡肯定能找到 restore[j]
{
append_v.push_back(restore[j]);
restore.pop_back();//這個千萬不要忘記
j--;//不要忘記了
}
append_v.push_back(restore[j]);//這個是最後一個
restore.pop_back();
reverse(append_v.begin(), append_v.end());
append_v.push_back(front);//現在就是完整的彈出案例了
for (int val : append_v)
{
qu.push(val);
}
//
}
else
{//直接加入到restore中
restore.push_back(front);
}
}
public:
/*
返回true代表nums1會贏 否則false
*/
bool doTractor(vector<int>& nums1,vector<int>& nums2)
{
vector<int> restore;
queue<int> qu1;
for (auto value : nums1) qu1.push(value);
queue<int> qu2;
for (auto value : nums2) qu2.push(value);
while (!qu1.empty()&&!qu2.empty())
{
cout << "qu1.size()=" << qu1.size() << " qu2.size()=" << qu2.size() << " restore.size()=" << restore.size() << endl;
doLoad(restore, qu1);//先將qu1牌放進restore中
doLoad(restore, qu2);將qu2牌放進restore中
}
cout << "結果返回值" << endl;
cout << "qu1.size()=" << qu1.size() << " qu2.size()=" << qu2.size() << " restore.size()=" << restore.size() << endl;
if (!qu1.empty())
{
return true;
}
else
{
return false;
}
}
};
int main()
{
vector<int> nums1{ 2,4,1,2,5,6 };
vector<int> nums2{3,1,3,5,6,4};
/*vector<int> nums1{ 1,5,2,6,2,1};
vector<int> nums2{ 3,10,12,15,16,18,100};*/
Solution s;
bool ret_b = s.doTractor(nums1, nums2);
/*for (auto one : ret_v)
{
cout << one << " ";
}*/
cout << ret_b << endl;
}