笔试强训Day01
【笔试强训】Day01
摘要
本文整理了笔试强训 Day01 的三道经典题目:数字统计、两个数组的交集、以及 点击消除。在数字统计中,我们通过枚举+数字拆分的方式统计指定范围内数字 2
出现的次数;在数组交集问题中,分别介绍了 排序+双指针 和 哈希表 两种解法,前者保证有序,后者实现简洁高效;而在点击消除题中,则利用 栈(string 模拟) 的特性实现了相邻元素的快速消除,避免了反转操作,使代码更加简洁。整体思路清晰,覆盖了 枚举、排序、哈希、栈 等常见算法技巧,适合作为刷题入门与复习笔记。
目录
一、数字统计
1.题目描述
2. 思路
枚举+数字拆分
通过cin输入L和R,表示范围,然后通过for循环遍历数字,将当前的值赋值给一个自定义的临时变量(否则循环会出错),然后通过%10取出个位数字,定义一个count,如果取出的数字是2,count就++,否则不变,最后通过 /10 更新一下当前查找的数字的值(拆分数字)。
#include<iostream>
using namespace std;
int main()
{
int count = 0;;
int L = 0;
int R = 0;
cin >> L >> R;
for (int i = L; i <= R ; i++)
{
int temp = i;
while (temp != 0)
{
if (temp % 10 == 2)
{
count++;
}
temp /= 10;
}
}
cout << count;
return 0;
}
二、两个数组的交集
1. 题目描述
2. 思路一
我们先将两个容器中的内容进行sort排序(默认是升序),然后创建一个新的容器result储存结果。首先我们定义i,j分别对应他们的下标,初始化为0;如果他们对应下标位置的数据相等,就push_back进result中,为了result中的数据重复,我们需要进行判断(result容器为空或者.back()返回最后一个数据的引用必须不等于他们数据相同时的值)。如何nums1[i]的值小于nums2[j]的值就i++,反之j++(因为他们已经排好序了)。
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// 定义类
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int i = 0;
int j = 0;
vector<int> result;
while (i < nums1.size() && j < nums2.size())
{
if (nums1[i] == nums2[j])
{
if (result.empty() || result.back() != nums1[i])
{
result.push_back(nums1[i]);
}
i++;
j++;
}
else if (nums1[i] < nums2[j])
{
i++;
}
else
{
j++;
}
}
return result;
}
};
int main() {
Solution s;
vector<int> nums1 = { 1, 2, 2, 1 };
vector<int> nums2 = { 2, 2 };
vector<int> ans = s.intersection(nums1, nums2);
cout << "交集结果: ";
for (int x : ans) {
cout << x << " ";
}
cout << endl;
return 0;
}
3. 思路二
哈希
将其中的一个数组丢进哈希表中,然后在另外一个数组中遍历,如果相同的数据话就push进一个新建的result容器中,为了避免重复还需要在哈希中将这个数据删除掉。(核心代码模式)
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
bool haxi[1010] = {0}; // 局部定义,避免污染
vector<int> result;
for (auto x : nums1) {
haxi[x] = true;
}
for (auto x : nums2) {
if (haxi[x]) {
result.push_back(x); // ✅ 这里要 push x,而不是 haxi[x]
haxi[x] = false; // ✅ 避免重复
}
}
return result;
}
};
三、点击消除
1. 题目描述
2.思路
我们可以利用范围for和栈,一个一个的遍历,当栈中为空或者栈顶元素和需要入栈元素不同的时候就入栈;或者当我们栈中有数据且入栈元素和栈中元素相同就把他们两个拿掉。但是的栈是后进先出,所以我以最后我们还需要reverse一下,所以我们可以直接选择用string模拟一个栈,还不需要反转字符。更加的简洁高效。
#include <iostream>
using namespace std;
int main() {
string s,st;
cin >> s;
for (auto x : s)
{
if (!st.empty() && st.back() == x)
{
st.pop_back();
}
else
{
st.push_back(x);
}
}
cout <<(st.size() == 0 ? "0" : st) <<endl;
return 0;
}
// 64 位输出请用 printf("%lld")
✨ 坚持用 清晰易懂的图解 + 代码语言, 让每个知识点都 简单直观 !
🚀 个人主页 :
🌱 代码仓库 :
📌 :
- 📖
- 🧩
- 💡
- 🐧
💬 座右铭 : “不患无位,患所以立。”