当前位置:网站首页>【剑指 Offer】从尾到头打印链表(栈思想)+ 数组中重复的数字(哈希映射)
【剑指 Offer】从尾到头打印链表(栈思想)+ 数组中重复的数字(哈希映射)
2022-07-16 03:04:00 【…狂奔的蜗牛~】
1.数组中重复的数字–》链接

【解题思路】:
我们看到nums中所有的数字都在0 ~(n-1)之间,所以我们可以利用哈希映射思想,定义一个大小为n的vector(v),数值都初始化为0,v的下标恰好对应0 ~(n-1)的每个数,然后遍历nums, nums[i]对应v下标的位置值++,即v[nums[i]]++,如果v[nums[i]]值大于一,说明在nums中出现了至少两次以上,因此返回nums[i].
代码实现:
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
int n=nums.size();
vector<int> v(n,0);
for(int i=0;i<n;i++)
{
v[nums[i]]++;
}
int i=0;
for(;i<=n;i++)
{
if(v[nums[i]]>1)
break;
}
return nums[i];
}
};
2.从尾到头打印链表 --》链接

【解题思路1】:
其实看到这个题目的直觉就是把链表里面的数据放入一个数组中,然后将数组的数据反一下就可以.
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> m;
while(head)
{
m.push_back(head->val);
head=head->next;
}
vector<int> v;
for(int i=m.size()-1;i>=0;i--)
{
v.push_back(m[i]);
}
return v;
}
};
【解题思路2】:
但是这样会多定义一个数组来存储数据使得空间复杂度增加,所以不实用。看到数据进去和出来顺序反着肯定想到的就是栈了,所以我们定义一个栈先把数据押入栈中,然后在将栈的数据存储的数组中即可。
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> v;
stack<int> s;
while(head)
{
s.push(head->val);
head=head->next;
}
while(!s.empty())
{
v.push_back(s.top());//取栈顶元素
s.pop();//删栈顶元素
}
return v;
}
};
边栏推荐
猜你喜欢

Network security -- Kali uses mdk3 to attack WiFi (detailed tutorial)

添加右键新建Markdown文件

Programming old driver takes you to play with completable future asynchronous programming

MGRE/OSPF综合实验

hcip第二天

HCIP第四天笔记

Qt编写物联网管理平台43-告警短信转发

Linux -- connecting to MySQL database and basic operations

【Golang | gRPC】使用TLS/SSL认证的gRPC服务
![[golang | GRC] GRC server streaming service end stream practice](/img/c6/b7a81894be1bb60d19311abfc07800.png)
[golang | GRC] GRC server streaming service end stream practice
随机推荐
MySQL foundation - add, delete, check and modify (Foundation)
ReversingKr-wp(7)
Automatic tracking tool bgmi
This article enables you to understand IIC, SPI and UART protocols
Use of zip/enumerate/map function
Gm3379 [noi2013 simulation] query
Principle of MySQL master-slave replication
Harbor: modify the default 172 network segment
Usage and difference between link reference and @import reference
MySQL基础——数据库约束与表的设计
Viewing binlog and relay log information
Pytorch——报错解决:RuntimeError: Expected all tensors to be on the same device, but found at least two
Runtimeerror: the size of tensor a (4) must match the size of tensor B (3) at non singleton
5g applications are accelerated, and cool Lehman VR live broadcast is born at the right time.
数字藏品系统开发,助力企业元宇宙场景营销
为什么 UDP 头只有 8 个字节
Google Earth Engine APP(GEE)—加载一个可查询的Spector
【Golang | gRPC】gRPC-Bidirectional Streaming双向流实战
自动追番工具BGmi
缓存穿透、缓存雪崩、缓存击穿?