当前位置:网站首页>[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)
边栏推荐
猜你喜欢

How can I become an irreplaceable programmer?

Upload local file trial version using SAP ui5 fileuploader control

【RTOS训练营】设备子系统、晚课学员提问

超全的开源Winform UI库,满足你的一切桌面开发需求!
![[RTOS training camp] continue the program framework, tick interrupt supplement, preview, after-school homework and evening class questions](/img/79/27e4709dd6381c8887e12a1a8da257.jpg)
[RTOS training camp] continue the program framework, tick interrupt supplement, preview, after-school homework and evening class questions

Redis (VIII) - redis enterprises' actual coupons spike

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

Database tools duel: heidisql and Navicat
![[zero based BLDC series] brushless DC motor control principle based on the zero crossing detection method of back EMF](/img/1d/00165635452245a4d1b557fba17c94.png)
[zero based BLDC series] brushless DC motor control principle based on the zero crossing detection method of back EMF
随机推荐
爬虫小操作
[RTOS training camp] course learning methods and structural knowledge review + linked list knowledge
matlab 移位操作基础
[RTOS training camp] course learning methods and C language knowledge (pointer, structure, function pointer, linked list) and student questions
如何才能修炼成一名不可替代的程序员?
The Chinese input (Pinyin input method) component created by lvgl official +100ask enables lvgl to support Chinese input!
Microwave oven rectifier diode cl01-12
IP地址能精确到哪步?动态IP及静态IP是什么?切换IP最常用的方法
Implementation process of adding loading effect to easycvr page
Practical exercise | find customers who buy more than n products within a given time range
Test the concept of left shift and right shift
Lock upgrade: no lock, bias lock, lightweight lock, heavyweight lock
用 QuestPDF操作生成PDF更快更高效!
【RTOS训练营】课程学习方法和结构体知识复习 + 链表知识
Unityvr robot Scene 3 gripper
JDBC implements the addition, deletion, modification and query of MySQL 8.0 database
With data-driven management transformation, the first year of science and technology was at the right time
It will be easier to implement MES system by doing well in these four stages
场景之分页查询设计
el-table滚动条设置