当前位置:网站首页>[Code] refers to the repeated number in the offer 03 array
[Code] refers to the repeated number in the offer 03 array
2022-07-26 01:00:00 【Quietly like big white】
Catalog
1、 subject
Find the repeated numbers in the array .
At a length of n Array of nums All the numbers in 0~n-1 Within the scope of . Some numbers in the array are repeated , But I don't know how many numbers are repeated , I don't know how many times each number has been repeated . Please find any duplicate number in the array .
Example 1:
Input :
[2, 3, 1, 0, 2, 5, 3]
Output :2 or 3
2、 Problem solving
The key to this question is to find 【 arbitrarily 】 A repeat Numbers that will do
Ideas : Hashtable / Set( Essentially a one-dimensional array )
Using the characteristics of data structure , Easy to think of Use hash table (Set) Record the numbers of the array , When a duplicate number is found, it returns directly .Algorithm flow :
initialization : newly build HashSet , Write it down as dict ;
Traversal array nums Every number in n :
When n stay dict in , Repeated description , Go straight back to Numbers n ;
Otherwise it would be Figures that have never appeared n Added to the dict in ;
Complexity analysis :
- Time complexity O(N): Traverse Using an array O(N) ,HashSet Add and find All elements are O(1) .
- Spatial complexity O(N) : HashSet Occupy O(N) The size of the extra space ( Additional space requested ).
Here is K God explains the problem-solving ideas in detail






def findRepeatNumber(nums):
dict = set()
for n in nums:
if n in dict:
return n
else:
dict.add(n)
nums = [2, 3, 1, 0, 2, 5, 3]
result = findRepeatNumber(nums)
print(result)
arr = input("please input some numbers with blank")
nums2 = [int(n) for n in arr.split()]
result2 = findRepeatNumber(nums2)
print(result2)result
2
please input some numbers with blank
2 3 1 0 2 5 3
2
** Process exited - Return Code: 0 **
Press Enter to exit terminalAdvanced thinking
The above method space complexity is O(N), Is there any way to reduce ?

In situ exchange
The title description has not been fully used , namely At a length of n Array of nums All the numbers in 0 ~ n-1 Within the scope of . This description means : Of array elements Indexes and value yes One to many The relationship between .
therefore , The array can be traversed and exchanged , Make the element Indexes And value One-to-one correspondence ( namely nums[i]=i ). thus , You can map the corresponding value through the index , Play a role equivalent to a dictionary .
That is, on the basis of the original array, make the index and the corresponding value of the index equal , The index is 0, The value is 0, The index is 1, The value is 1.
Algorithm flow :( The key is conditional judgment )
Traversal array nums , Let the initial value of index be n=0 :if nums[n] =n : Indicates that this number is already in the corresponding index position , There is no need to exchange , So skip , Continue to traverse and execute ;
if nums[nums[n]] =nums[n] : For index nums[n] Place and index n The element values at are nums[n] , That is, find a set of duplicate values , Return this value nums[n] ;
otherwise : The exchange index is i and nums[n] The element value of , Exchange this number to the corresponding index position .Complexity analysis :
Time complexity O(N): Traverse Using an array O(N) , Judgment and exchange of each round of traversal Operation and use O(1) .
Spatial complexity O(1) : Use the extra space of constant complexity .
Code
def findRepeatNumber(nums):
n = 0
while n < len(nums):
if nums[n] == n:
n += 1
continue
if nums[nums[n]] == nums[n]:
return nums[n]
else:
nums[nums[n]], nums[n] = nums[n], nums[nums[n]]
nums = [2, 3, 1, 0, 2, 5, 3]
result = findRepeatNumber2(nums)
print(result)
arr = input("please input some numbers with blank")
nums2 = [int(n) for n in arr.split()]
result2 = findRepeatNumber(nums2)
print(result2)result
2
please input some numbers with blank
2 3 1 0 2 5 3
2
** Process exited - Return Code: 0 **
Press Enter to exit terminal3、 Reference resources
2022 How to prepare for the algorithm post ? - You know
2023 Summary of the knowledge of the school recruitment algorithm post - You know
Machine learning interview preparation
GitHub - rushter/MLAlgorithms: Minimal and clean examples of machine learning algorithms implementations 【 The finger of the sword offer】 high frequency ML/DL Interview questions ( Continuous updating )_ Mountaintop evening view blog -CSDN Blog [email protected]GitHub - scutan90/DeepLearning-500-questions: Deep learning 500 ask , The common probability knowledge in the form of question and answer 、 linear algebra 、 machine learning 、 Deep learning 、 Computer vision and other hot issues , To help yourself and readers in need . The book is divided into 18 Chapters ,50 More than ten thousand words . Due to limited level , The readers are kindly requested to criticize and correct the improper parts in the book . To be continued ............ If you want to cooperate , contact [email protected] copyright , Violation of rights will be prosecuted Tan 2018.06GitHub - geektutu/interview-questions: machine learning / Deep learning /Python/Go Language interview questions pen test questions (Machine learning Deep Learning Python and Golang Interview Questions)GitHub - amusi/Deep-Learning-Interview-Book: Deep learning interview guide ( Including mathematics 、 machine learning 、 Deep learning 、 Computer vision 、 Natural language processing and SLAM Wait for the direction )
Online Python - IDE, Editor, Compiler, Interpreter
GitHub - greyireland/algorithm-pattern: Algorithm template , The most scientific way to brush questions , The fastest way to brush questions , You deserve it ~ GitHub - zhulintao/CodingInterviewChinese2: 《 The finger of the sword Offer》 The second version of source code (Clone from: https://github.com/zhedahht/CodingInterviewChinese2)
边栏推荐
- [laser principle and application-4]: internal structure and working principle of laser
- Database tools duel: heidisql and Navicat
- 109. 使用 SAP UI5 FileUploader 控件上传本地文件
- 【Code】剑指offer 03数组中重复的数字
- With data-driven management transformation, the first year of science and technology was at the right time
- 200 yuan a hair dryer, only a week, to achieve 2million?
- 游戏思考17:寻路引擎recast和detour学习二:recast导航网格生成流程及局限性
- jupyter更改主界面并且导入数据集
- Django database addition, deletion, modification and query
- Upload local file trial version using SAP ui5 fileuploader control
猜你喜欢

【RTOS训练营】环形缓冲区、AT指令、预习安排和晚课提问

【RTOS训练营】关于上课和答疑

JDBC实现MySQL8.0数据库的增删改查
![[install software after computer reset] software that can search all files of the computer, the best screenshot software in the world, free music player, JDK installation, MySQL installation, installa](/img/d6/45f17c50f13d0bae1d14b317f9ae30.png)
[install software after computer reset] software that can search all files of the computer, the best screenshot software in the world, free music player, JDK installation, MySQL installation, installa

Embedded development: tips and tricks -- seven tips for designing powerful boot loader
![[RTOS training camp] learn C language from a higher perspective](/img/4c/bbbec489abb781a1de1e99bbf12c6f.png)
[RTOS training camp] learn C language from a higher perspective

JDBC implements the addition, deletion, modification and query of MySQL 8.0 database

Implementation process of adding loading effect to easycvr page
![[IJCAI 2022] parameter efficient large model sparse training method, which greatly reduces the resources required for sparse training](/img/56/7a49f9c825d88a31b980a5fae50951.png)
[IJCAI 2022] parameter efficient large model sparse training method, which greatly reduces the resources required for sparse training

200 yuan a hair dryer, only a week, to achieve 2million?
随机推荐
【RTOS训练营】课程学习方法和C语言知识(指针、结构体、函数指针、链表)和学员问题
The ultra comprehensive open source WinForm UI library meets all your desktop development needs!
【RTOS训练营】环形缓冲区、AT指令、预习安排和晚课提问
《自然语言处理实战入门》深度学习基础 ---- attention 注意力机制 ,Transformer 深度解析与学习材料汇总
编程学习过程中有哪些快速提高编程技巧的方法?
With data-driven management transformation, the first year of science and technology was at the right time
[RTOS training camp] problems of evening students
MMOCR使用指南
爬虫小操作
Tensorflow 2 detailed explanation (TF ecosystem, installation, housekeeping, basic operation)
Embedded development: tips and tricks -- seven tips for designing powerful boot loader
EasyCVR页面添加Loading加载效果的实现过程
It will be easier to implement MES system by doing well in these four stages
Nanjie's embarrassment
Database tools duel: heidisql and Navicat
【RTOS训练营】作业讲解、队列和环形缓冲区、队列——传输数据、队列——同步任务和晚课提问
[translation paper] analysis of land cover classification using multi wavelength lidar system (2017)
中心对称的二进制模式CSLBP,matlab
Open download! Alibaba Devops Practice Manual
Timeout settings for feign and hystrix