67. 旅行终点站(简单)
题目要求:
给定一份旅游线路图,该线路图中的旅行线路用数组 paths 表示,其中 paths[i] = [cityAi, cityBi] 表示该线路将会从 cityAi 直接前往 cityBi 。请你找出这次旅行的终点站,即没有任何可以通往其他城市的线路的城市。
题目数据保证线路图会形成一条不存在循环的线路,因此恰有一个旅行终点站。
题目分析:
由于cityAi为起点,终点只会在cityBi中出现,先存储cityAi的信息,然后查看cityBi是否在这些信息中,不在的cityBi即为终点。
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_set>
class Solution
{
public:
string destCity(vector<vector<string>>& paths)
{
unordered_set<string> citiesA;
for (auto &path : paths)
{
citiesA.insert(path[0]); // 将每条路径的起点插入citiesA
}
for (auto &path : paths)
{
if (!citiesA.count(path[1])) // 判断citiesA中是否有每条路径的终点,即判断终点是否在起点的位置出现过
{
return path[1];
}
}
return "";
}
};
int main()
{
vector<vector<string>> paths = { {"London","New York"}, {"New York","Lima"}, {"Lima","Sao Paulo"} };
Solution s;
cout << "路径为:" << endl;
for (auto &path : paths)
{
for (auto &point : path)
{
cout << point << ", ";
}
cout << endl;
}
cout << endl;
string res = s.destCity(paths);
cout << "旅行的终点是:" << res << endl;
system("pause");
return 0;
}
68. 复写零(简单)
题目要求:
给定一个长度固定的整数数组arr
,请将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。
注意:请不要在超过该数组长度的位置写入元素。请对输入的数组就地
进行上述修改,不要从函数返回任何东西。
题目分析:
双指针,一个指针记录原数组元素位置,一个指针记录复写零后元素位置
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
class Solution
{
public:
void duplicateZeros(vector<int>& arr)
{
int n = arr.size();
int top = 0; // top指向更新后的数组顶部
int i = -1; // 指针指向第一个元素前面的位置
while (top < n)
{
i++;
if (arr[i] != 0)
{
top++;
}
else
{
top += 2;
}
}
int j = n - 1; // 指针指向新数组的最后一个元素
if (top == n + 1) // 如果条件成立,说明top最后遍历的元素为0
{
arr[j] = 0; // 将原数组的最后一个元素改为0
j--; // 新数组的指针向前移动一位
i--; // 旧数组的指针向前移动一位
}
while (j >= 0)
{
arr[j] = arr[i]; // 将原数组的值依次赋值给新数组
j--;
if (!arr[i]) // 如果原数组的值为0,将新数组的下一个元素继续赋0
{
arr[j] = arr[i];
j--;
}
i--; // i--; // 旧数组的指针向前移动一位
}
}
};
int main()
{
vector<int> arr = { 1,0,0,3,0,4,5,0 };
Solution s;
cout << "复写零之前:";
for (int num : arr)
{
cout << num << ", ";
}
cout << endl;
s.duplicateZeros(arr);
cout << "复写零之后:";
for (int num : arr)
{
cout << num << ", ";
}
cout << endl;
system("pause");
return 0;
}
69. 统计有序矩阵中的负数(简单)
题目要求:
给定一个m * n
的矩阵grid
,矩阵中的元素无论是按行还是按列,都以非严格递减顺序排列。 请你统计并返回grid
中 负数 的数目。
题目分析:
二分查找
题目解答:
#include <iostream>
using namespace std;
#include <string>
#include <vector>
#include <algorithm>
class Solution {
public:
int countNegatives(vector<vector<int>>& grid) {
int num = 0;
for (auto x : grid)
{
int l = 0, r = (int)x.size() - 1, pos = -1;
while (l <= r)
{
int mid = l + ((r - l) >> 1);
if (x[mid] < 0)
{
pos = mid;
r = mid - 1;
}
else
l = mid + 1;
}
if (~pos)
{
num += (int)x.size() - pos;
}
}
return num;
}
};
int main()
{
vector<vector<int>> grid = { {4,3,2,-1}, {3,2,1,-1}, {1,1,-1,-2}, {-1,-1,-2,-3} };
Solution s;
cout << "原矩阵为:" << endl;
for (auto x : grid)
{
for (auto y : x)
{
cout << y << ", ";
}
cout << endl;
}
cout << endl;
int res = s.countNegatives(grid);
cout << "矩阵中有" << res << "个负数" << endl;
system("pause");
return 0;
}