当前位置:网站首页>Leetcode540: a single element in an ordered array
Leetcode540: a single element in an ordered array
2022-07-03 17:29:00 【Slow ploughing of stupid cattle】
Catalog
Treatment of boundary conditions
1. Title Description
Give you an ordered array of integers only , Each of these elements will appear twice , Only one number will appear once .
Please find and return the number that only appears once .
The solution you design must meet O(log n) Time complexity and O(1) Spatial complexity .
Example 1:
Input : nums = [1,1,2,3,3,4,4,8,8]
Output : 2
Example 2:
Input : nums = [3,3,7,7,10,11,11]
Output : 10
Tips :
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^5
source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/single-element-in-a-sorted-array
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
2. Problem solving analysis
2.1 Ideas 1
If a number performs bitwise XOR with itself, it will get 0. therefore , As long as all the numbers in the array are bitwise XOR, the final result is the required single element .
Intuitive approach ( Assume that the array is a) Namely ,a(0) and a(1) Do exclusive or operations , The result is similar to a[2] Do exclusive or operations ,..., Until finally with a[N-1] Do exclusive or operations , That is, get the desired result . But this realization , Although the space complexity meets O(1) The requirements of , Time complexity needs O(N) The computational complexity of , Does not meet the requirements of the topic O(log(N)) Complexity requirements .
2.2 Ideas 2
As the required time complexity is O(log(N)), So it's natural to imagine dichotomy ( What else can there be besides dichotomy O(log(N)) The time complexity ?). It has been made clear in the design that the input array is an ordered array , Therefore, the number appearing twice must appear adjacent , The lonely number is different from its front number and its back number . The other numbers in the array are either the same as the number before it or the number after it . Based on this, we can find the lonely number based on dichotomy .
left and right Update
The key point of dichotomy search is left and right Update . Take... From the conventional dichotomy mid=(left+right)//2("//" means integer division in python) that will do . And this topic is about mid The treatment of is also a little special .
Because there must be an even number in front of the lonely number , Then there must be even numbers , So the subscript of lonely number ( Consider from 0 At the beginning zero-indexing) It must be even . So if mid=(left+right)//2 For an odd number , Can take mid=mid-1 Adjust to an even number to handle .
For a mid, If nums[mid] If it is not equal to the number before it and the number after it , Then it is the number you are looking for . If not , Is the search interval the left half or the right half ?
If ,nums[mid] be equal to nums[mid-1] Words , Because the right half is even , The only lonely number cannot appear in the even number , So the next step is to search the left half . here , It should be maintained left unchanged , And will be right Updated to mid( Be careful , No mid-1, Because we must keep the length of the search interval odd . This is also slightly different from the general dichotomy ).
conversely , If nums[mid] be equal to nums[mid+1] Words , The next step is to search the right half . At this time, we should keep right unchanged , And will be left Updated to mid.
Treatment of boundary conditions
The above treatment should be compared nums[mid],nums[mid-1] as well as nums[mid+1]. When mid=0 perhaps mid=N-1 when , Appropriate boundary processing is needed to avoid cross-border errors .
Of course , And don't forget , There is only one number input .
Besides , The case that the length of the input array is even is an exception , You need to consider the input legitimacy check .
3. Code implementation
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
N = len(nums)
if N==1:
return nums[0]
if N%2 == 0:
return None
left = 0
right = N - 1
# Boundary check
if nums[0] != nums[1]:
return nums[0]
if nums[-1] != nums[-2]:
return nums[-1]
cnt = 0
while left <= right:
if left == right:
return nums[left]
mid = (left+right) // 2
# print(left,right,mid)
if mid%2 == 1:
mid = mid - 1
if (nums[mid] != nums[mid-1]) and (nums[mid] != nums[mid+1]):
return nums[mid]
if nums[mid] == nums[mid-1]:
right = mid
else:
left = mid
if __name__ == '__main__':
sln = Solution()
nums = [1,1,2,3,3,4,4,8,8]
print(sln.singleNonDuplicate(nums))
nums = [3,3,7,7,10,11,11]
print(sln.singleNonDuplicate(nums))
nums = [3,3,7,7,9,9,10]
print(sln.singleNonDuplicate(nums))
nums = [2,3,3,4,4,8,8]
print(sln.singleNonDuplicate(nums))
nums = [2]
print(sln.singleNonDuplicate(nums))
nums = [2,2,3,3]
print(sln.singleNonDuplicate(nums))
边栏推荐
- 1147_ Makefile learning_ Target files and dependent files in makefile
- How to read the source code [debug and observe the source code]
- SVN如何查看修改的文件记录
- [combinatorics] recursive equation (general solution structure of recursive equation with multiple roots | linear independent solution | general solution with multiple roots | solution example of recu
- HP 阵列卡排障一例
- Leetcode Valentine's Day Special - looking for a single dog
- New library online | cnopendata complete data of Chinese insurance institution outlets
- C language string practice
- [RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework
- 1146_ SiCp learning notes_ exponentiation
猜你喜欢
鸿蒙第三次培训
IntelliJ 2021.3 short command line when running applications
[RT thread] construction and use of --hwtimer of NXP rt10xx device driver framework
Cross border e-commerce: advantages of foreign trade enterprises in overseas social media marketing
Swm32 series Tutorial 4 port mapping and serial port application
Vs2013 has blocked the installer, and ie10 needs to be installed
UE4 official charging resources, with a total price of several thousand
Unity notes unityxr simple to use
vs2013已阻止安装程序,需安装IE10
Redis: operation commands for list type data
随机推荐
RDS数据库的监测页面在哪看?
大变局!全国房价,跌破万元大关
数仓任务里面 跑SQL任务的时候用的数据库账号是在哪里配置的
Notes on problems -- watching videos on edge will make the screen green
Apache服务挂起Asynchronous AcceptEx failed.
IntelliJ 2021.3 short command line when running applications
Is AI too slow to design pictures and draw illustrations? 3 sets of practical brushes to save you
在iptables防火墙下开启vsftpd的端口
Automata and automatic line of non-standard design
RedHat 6.2 configuring ZABBIX
[combinatorics] recursive equation (example of solving recursive equation without multiple roots | complete process of solving recursive equation without multiple roots)
Web-ui automated testing - the most complete element positioning method
SVN如何查看修改的文件记录
What is your income level in the country?
Kotlin learning quick start (7) -- wonderful use of expansion
Leetcode 669 pruning binary search tree -- recursive method and iterative method
New library online | cnopendata China bird watching record data
Free data | new library online | cnopendata complete data of China's insurance intermediary outlets
[RT thread] NXP rt10xx device driver framework -- RTC construction and use
The difference between get and post