当前位置:网站首页>Leetcode (540) -- a single element in an ordered array
Leetcode (540) -- a single element in an ordered array
2022-07-03 02:05:00 【SmileGuy17】
Leetcode(540)—— A single element in an ordered array
subject
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 ) O(\log n) O(logn) Time complexity and O ( 1 ) O(1) 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 1 1 <= nums.length <= 1 0 5 10^5 105
- 0 0 0 <= nums[i] <= 1 0 5 10^5 105
Answer key
Method 1 : Binary search of full array
Ideas
Because the given array is ordered And Regular elements always appear in pairs , So if you don't consider “ special ” Of a single element , We have a conclusion : The subscript corresponding to the first of the paired elements must be even , The subscript corresponding to the second of the paired elements must be odd .
then Then consider the case where there is a single element , If the subscript of a single element is x x x, So subscript x x x Before ( On the left ) The position of still satisfies the above conclusion , And subscripts x x x after ( On the right ) Due to x x x Insertion , Cause the conclusion to flip .
Suppose that the element that appears only once is in the subscript x x x, Because every other element appears twice , So subscript x x x There are even elements on the left and right of , The length of the array is odd .
Because arrays are ordered , Therefore, the same elements in the array must be adjacent . For subscripts x x x The subscript on the left y y y, If nums [ y ] = nums [ y + 1 ] \textit{nums}[y] = \textit{nums}[y + 1] nums[y]=nums[y+1], be y y y It must be an even number ; For subscripts x x x The subscript on the right z z z, If nums [ z ] = nums [ z + 1 ] \textit{nums}[z] = \textit{nums}[z + 1] nums[z]=nums[z+1], be z z z It must be odd . Because of subscript x x x Is the boundary between the parity of the starting subscript of the same element , Therefore, we can use the binary search method to find the subscript x x x.
At the beginning , The left bound of binary search is 0 0 0, The right boundary is the maximum subscript of the array . Take the average value of the left and right boundaries each time mid \textit{mid} mid As a subscript to be judged , according to mid \textit{mid} mid The parity of determines the comparison with the adjacent elements on the left or right :
- If mid \textit{mid} mid It's even , Then compare nums [ mid ] \textit{nums}[\textit{mid}] nums[mid] and nums [ mid + 1 ] \textit{nums}[\textit{mid} + 1] nums[mid+1] Whether it is equal or not ;
- If mid \textit{mid} mid Is odd , Then compare nums [ mid − 1 ] \textit{nums}[\textit{mid} - 1] nums[mid−1] and nums [ mid ] \textit{nums}[\textit{mid}] nums[mid] Whether it is equal or not .
If the result of the above comparison of adjacent elements is equal , be mid < x \textit{mid} < x mid<x, Adjust the left border , otherwise mid ≥ x \textit{mid} \ge x mid≥x, Adjust the right border . After adjusting the boundary, continue the binary search , Until the subscript is determined x x x Value . Get the subscript x x x After the value of , nums [ x ] \textit{nums}[x] nums[x] That is, the element that appears only once .
details ( Tips )—— You don't have to judge mid \textit{mid} mid Parity
Using the properties of bitwise XOR , You can get mid \textit{mid} mid And adjacent numbers , among ⊕ \oplus ⊕ Is a bitwise XOR operator :
- When mid \textit{mid} mid When it's even , mid + 1 = mid ⊕ 1 \textit{mid} + 1 = \textit{mid} \oplus 1 mid+1=mid⊕1;
- When mid \textit{mid} mid It's an odd number , mid − 1 = mid ⊕ 1 \textit{mid} - 1 = \textit{mid} \oplus 1 mid−1=mid⊕1.
So in the process of binary search , You don't have to judge mid \textit{mid} mid Parity , mid \textit{mid} mid and mid ⊕ 1 \textit{mid} \oplus 1 mid⊕1 That is, the two subscripts of each element to be compared .
because 0 ⊕ 1 0 \oplus 1 0⊕1 As the result of the 1 1 1 , So don't worry that the left side will cross the border . Again because m i d = ( l + r ) / 2 mid = (l+r)/2 mid=(l+r)/2 therefore m i d mid mid The value of is rounded down , There will be no right access array out of bounds .
Code implementation
Leetcode Official explanation :
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int l = 0, r = nums.size()-1, mid;
while(l < r){
mid = (l+r)/2;
if(nums[mid] == nums[mid^1])
l = mid + 1;
else r = mid;
}
return nums[l];
}
};
My own ( Judge by length ):
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
// find mid Judge the length of the left and right intervals , Find the odd length and continue to search
// such as [1,1,2,3,3,4,4] mid For the first time 3, Then judge whether the length of it and the right interval of the same value is odd , Yes, find , If not, find another
int l = 0, r = nums.size()-1, mid, n = nums.size();
while(l <= r){
mid = (l+r)/2;
if(mid != 0 && nums[mid] == nums[mid-1]){
if((r-mid)%2 == 0) r = mid-2;
else l = mid+1;
}else if(mid != n-1 && nums[mid] == nums[mid+1]){
if((r-mid+1)%2 == 0) r = mid-1;
else l = mid+2;
}else break;
}
return nums[mid];
}
};
Complexity analysis
Time complexity : O ( l o g n ) O(logn) O(logn), among n n n It's an array nums \textit{nums} nums The length of . You need to binary search in the range of the whole array , The time complexity of binary search is O ( log n ) O(\log n) O(logn).
Spatial complexity : O ( 1 ) O(1) O(1).
Method 2 : Binary search of even subscripts
Ideas
Because the subscript of the element that appears only once x x x There are even elements on the left of , So subscript x x x It must be an even number , You can find it in binary within the even subscript range . The goal of binary search is Find satisfaction nums [ x ] ≠ nums [ x + 1 ] \textit{nums}[x] \ne \textit{nums}[x + 1] nums[x]=nums[x+1] The smallest even subscript of x x x, Then subscript x x x The element at is an element that appears only once .
At the beginning , The left bound of binary search is 0 0 0, The right boundary is the maximum even subscript of the array , Because the length of the array is odd , Therefore, the maximum even subscript of the array is equal to the length of the array minus 1 1 1.
Take the average value of the left and right boundaries each time mid \textit{mid} mid As a subscript to be judged , If mid \textit{mid} mid If it is an odd number, it will mid \textit{mid} mid reduce 1 1 1, Make sure mid \textit{mid} mid It's even .
Compare nums [ mid ] \textit{nums}[\textit{mid}] nums[mid] and nums [ mid + 1 ] \textit{nums}[\textit{mid} + 1] nums[mid+1] Whether it is equal or not , If they are equal mid < x \textit{mid} < x mid<x, Adjust the left border , otherwise mid ≥ x \textit{mid} \ge x mid≥x, Adjust the right border . After adjusting the boundary, continue the binary search , Until the subscript is determined x x x Value .
Get the subscript x x x After the value of , nums [ x ] \textit{nums}[x] nums[x] That is, the element that appears only once .
details
consider mid \textit{mid} mid and 1 1 1 The result of bitwise sum operation , among & \& & It's the bitwise and operator :
- When mid \textit{mid} mid When it's even , mid & 1 = 0 \textit{mid}~\&~1 = 0 mid & 1=0;
- When mid \textit{mid} mid It's an odd number , mid & 1 = 1 \textit{mid}~\&~1 = 1 mid & 1=1.
So in getting mid \textit{mid} mid After the value of , take mid \textit{mid} mid The value of minus mid & 1 \textit{mid}~\&~1 mid & 1, To ensure the new mid \textit{mid} mid It's even . If the original mid \textit{mid} mid If it is an even number, the value remains the same , If the original mid \textit{mid} mid If it is an odd number, the value is minus 1 1 1.
Code implementation
Leetcode Official explanation :
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int low = 0, high = nums.size() - 1;
while (low < high) {
int mid = (high - low) / 2 + low;
mid -= mid & 1;
if (nums[mid] == nums[mid + 1]) {
low = mid + 2;
} else {
high = mid;
}
}
return nums[low];
}
};
Complexity analysis
Time complexity : O ( log n ) O(\log n) O(logn), among n n n It's an array nums \textit{nums} nums The length of . You need to find two points in the even subscript range , The time complexity of binary search is O ( log n ) O(\log n) O(logn).
Spatial complexity : O ( 1 ) O(1) O(1).
边栏推荐
- Huakaiyun | virtual host: IP, subnet mask, gateway, default gateway
- 查询商品案例-页面渲染数据
- Redis: simple use of redis
- Network security - Trojan horse
- Network security - scan
- elastic stack
- [error record] an error is reported in the fluent interface (no mediaquery widget ancestor found. | scaffold widgets require a mediaquery)
- Basic operation of view
- String replace space
- MySQL learning 03
猜你喜欢
Depth (penetration) selector:: v-deep/deep/ and > > >
Take you ten days to easily complete the go micro service series (II)
elastic stack
[shutter] pull the navigation bar sideways (drawer component | pageview component)
What are MySQL locks and classifications
Deep learning notes (constantly updating...)
Some functions of applet development
[Appendix 6 Application of reflection] Application of reflection: dynamic agent
Bottleneck period must see: how can testers who have worked for 3-5 years avoid detours and break through smoothly
使用Go语言实现try{}catch{}finally
随机推荐
Query product cases - page rendering data
可视化yolov5格式数据集(labelme json文件)
Button button adaptive size of wechat applet
网络安全-ACL访问控制列表
The technology boss is ready, and the topic of position C is up to you
Network security - phishing
Socket编程
查询商品案例-页面渲染数据
In the face of difficult SQL requirements, HQL is not afraid
Anna: Beibei, can you draw?
[Appendix 6 Application of reflection] Application of reflection: dynamic agent
Huakaiyun | virtual host: IP, subnet mask, gateway, default gateway
DML Foundation
CFdiv2-Fixed Point Guessing-(區間答案二分)
疫情當頭,作為Leader如何進行團隊的管理?| 社區征文
[camera topic] complete analysis of camera dtsi
DQL basic operation
Hard core observation 547 large neural network may be beginning to become aware?
Leetcode 183 Customers who never order (2022.07.02)
Comment communiquer avec Huawei Cloud IOT via le Protocole mqtt