当前位置:网站首页>287. Looking for repeats - fast and slow pointer
287. Looking for repeats - fast and slow pointer
2022-07-05 08:35:00 【Mr Gao】
287. Look for repetitions
Given an inclusion n + 1 Array of integers nums , The numbers are all in [1, n] Within the scope of ( Include 1 and n), We know that there is at least one duplicate integer .
hypothesis nums Only A repeated integer , return The number of repetitions .
The solution you design must Don't modify Array nums And only constant level O(1) Extra space .
Example 1:
Input :nums = [1,3,4,2,2]
Output :2
Example 2:
Input :nums = [3,1,3,4,2]
Output :3
For this question
First , You can use the fast and slow pointer to find and change
If there is a change , Then the fast and slow pointers will meet in the ring , But the point of meeting , Not necessarily the starting point of change
Put the fast pointer back head, The speed pointer moves in the same step , Final , Will meet at the entrance of the ring
You blew the wind when I came , I returned to my hometown , Unexpectedly, we met again at the origin
int findDuplicate(int* nums, int numsSize) {
int fast = 0;
int slow = 0;
while (true) {
fast = nums[nums[fast]];
slow = nums[slow];
if (fast == slow) {
fast = 0;
while (fast != slow) {
fast = nums[fast];
slow = nums[slow];
}
return slow;
}
}
}
边栏推荐
- What are the test items of power battery ul2580
- 图解八道经典指针笔试题
- Guess riddles (142)
- 猜谜语啦(2)
- Apaas platform of TOP10 abroad
- Take you to understand the working principle of lithium battery protection board
- 猜谜语啦(11)
- STM32 --- NVIC interrupt
- Several problems to be considered and solved in the design of multi tenant architecture
- U8g2 drawing
猜你喜欢
实例005:三数排序 输入三个整数x,y,z,请把这三个数由小到大输出。
Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)
UE pixel stream, come to a "diet pill"!
每日一题——替换空格
99 multiplication table (C language)
MATLAB小技巧(28)模糊綜合評價
Summary of SIM card circuit knowledge
MHA High available Cluster for MySQL
Working principle and type selection of common mode inductor
Installation and use of libjpeg and ligpng
随机推荐
Guess riddles (2)
QEMU demo makefile analysis
剑指 Offer 09. 用两个栈实现队列
实例009:暂停一秒输出
[three tier architecture and JDBC summary]
TypeScript手把手教程,简单易懂
Charge pump boost principle - this article will give you a simple understanding
QEMU STM32 vscode debugging environment configuration
MATLAB小技巧(28)模糊綜合評價
STM32 single chip microcomputer - external interrupt
MySQL之MHA高可用集群
Cinq détails de conception du régulateur de tension linéaire
Lori remote control LEGO motor
Speech recognition learning summary
Business modeling of software model | stakeholders
關於線性穩壓器的五個設計細節
Stm32--- systick timer
Esphone retrofits old fans
C language data type replacement
实例006:斐波那契数列