当前位置:网站首页>[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)
边栏推荐
- 游戏思考17:寻路引擎recast和detour学习二:recast导航网格生成流程及局限性
- 什么是信息化?什么是数字化?这两者有什么联系和区别?
- How can MySQL just duplicate data?
- 嵌入式开发:技巧和窍门——设计强大的引导加载程序的7个技巧
- 【RTOS训练营】GPIO知识和预习安排 + 晚课提问
- Distributed transaction and at mode principle of Seata
- Curd used by hyperf
- Cf1494f delete the edges (Euler circuit)
- LVGL官方+100ASK合力打造的中文输入(拼音输入法)组件,让LVGL支持中文输入!
- Leetcode notes 20. valid parentheses
猜你喜欢

JDBC实现MySQL8.0数据库的增删改查

什么是信息化?什么是数字化?这两者有什么联系和区别?

【MATLAB appdesigner】27_ How to debug and view variables in appdesigner? (examples + skills)

独家下载|《阿里云MaxCompute百问百答》 解锁SaaS模式云数据仓库尽在本电子手册!

【RTOS训练营】课程学习方法和结构体知识复习 + 链表知识

Travel + strategy accelerated landing, jietu new product matrix exposure

The ultra comprehensive open source WinForm UI library meets all your desktop development needs!

EasyCVR页面添加Loading加载效果的实现过程

【RTOS训练营】任务调度(续)、任务礼让、调度总结、队列和晚课提问

109. Upload local files using SAP ui5 fileuploader control
随机推荐
[array related methods in numpy]
[RTOS training camp] learn C language from a higher perspective
ZK-Rollups工作原理
SQL statement exercise
【RTOS训练营】程序框架、预习、课后作业和晚课提问
Solve the problem that when the background image is set to be 100% full, when the horizontal scroll bar appears in the zoom browser, the part of the background image beyond the scroll bar is not full
The Chinese input (Pinyin input method) component created by lvgl official +100ask enables lvgl to support Chinese input!
How to copy and paste QT? (QClipboard)
How can a team making facial mask achieve a revenue of more than 1 million a day?
It will be easier to implement MES system by doing well in these four stages
【RTOS训练营】课程学习方法和C语言知识(指针、结构体、函数指针、链表)和学员问题
Nanjie's embarrassment
Open download! Alibaba Devops Practice Manual
Implementation process of adding loading effect to easycvr page
Oauth2 and JWT
985 associate professors in Colleges and universities sun their annual salary, and the provident fund tops the monthly salary of ordinary people. Netizen: it is worthy of being in Shanghai
【RTOS训练营】I2C和UART知识和预习安排 + 晚课提问
jupyter更改主界面并且导入数据集
Azure synapse analytics Performance Optimization Guide (1) -- optimize performance using ordered aggregate column storage indexes
使用 SAP UI5 FileUploader 控件上传本地文件试读版