当前位置:网站首页>Single element of an ordered array
Single element of an ordered array
2022-07-01 18:13:00 【Ustinian%】
Single element of an ordered array
Topic link :540. A single element in an ordered array
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 <= 105
0 <= nums[i] <= 105
Solution 1 :
Because in addition to that single element in the array , Other elements appear in pairs , So we can use XOR , Use a variable to XOR all the numbers in the array once , The final result is the single element .
x^x = 0,x^0 = x;
Time complexity O(N)
Spatial complexity O(1)
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
// Record the final answer
int ans = 0;
for(int i = 0;i<nums.size();i++)
{
ans^=nums[i];
}
return ans;
}
};
Solution 2 :
We can also use the dichotomy method to solve this problem .
We can think about it like this : Before this single element existed , The numbers of arrays are all 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 .
When we insert this single element into the array , The first half of the single element will still have the above conclusion , However, the latter half of a single element will cause the conclusion to flip due to the insertion of the single element . Thus there are : The subscript corresponding to the first of the paired elements must be odd , The subscript corresponding to the second of the paired elements must be even .
Therefore, the duality of our problem comes out , We can according to the equinox mid To discuss the situation according to the parity of :
- If mid The subscript is even , According to the initial conclusion , Under normal circumstances, the value of the even subscript will be equal to the value of the next number . So if this condition is met , Prove that the single element is not mid Left side , It should be in mid The right side of does not include mid, So we update the interval to [mid+1,right], On the contrary, if the current mid If it is not equal to the value of the next number , Then the value of a single element should be mid The left side of includes mid, Therefore, the update interval is [left,mid]
- If mid Subscripts are odd , According to the initial conclusion , Under normal circumstances, the value of an odd subscript will be equal to the value of its previous number . So if this condition is met , Prove that the single element is not mid Left side , It should be in mid The right side of does not include mid, So we update the interval to [mid+1,right], On the contrary, if the current mid If it is not equal to the value of its previous number , Then the value of a single element should be mid The left side of includes mid, Therefore, the update interval is [left,mid]
Time complexity O(logN)
Spatial complexity O(1)
class Solution {
public:
int singleNonDuplicate(vector<int>& nums) {
int n = nums.size();
// It's a special verdict
if(n==1)
{
return nums[0];
}
// Dichotomous thinking
// Before the existence of this single element , The numbers in the array are all in pairs , So the number of pairs The subscript of the first number is even, and the subscript of the second number is odd
// But after inserting this single element into a certain position , The first half of the data of the single element will still keep the subscript of the first number even , The subscript of the second number is odd
// But in the second half of the single element, the nature of the data will change
// The second half of the data will become : The subscript of the first number of paired data is odd , The subscript of the second number is even
int left = 0;
int right = n-1;
while(left<right)
{
int mid = left+(right-left)/2;
// If mid The value of the subscript is even
if((mid&1)==0)
{
// If mid Subscript value and mid+1 The values of subscripts are equal
// The number that proves to occur only once appears in mid The right side of does not include mid
// Therefore, the update interval is [mid+1,right]
if(mid+1<n&&nums[mid]==nums[mid+1])
{
left = mid+1;
}
// Otherwise, the update interval is [left,mid]
else
{
right = mid;
}
}
// If mid The value of the subscript is an odd number
else
{
// If mid Subscript value and mid-1 The value of is equal
// The number that proves to appear only once is mid The right side of does not include mid
// Therefore, the update interval is [mid+1,right]
if(mid-1>=0&&nums[mid-1]==nums[mid])
{
left = mid+1;
}
// Otherwise, the update interval is [left,mid]
else
{
right = mid;
}
}
}
return nums[right];
}
};
边栏推荐
- MySQL -- explain performance optimization
- Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse
- From comedians to NBA Zhan Huang, check the encrypted advertisements during this super bowl
- Apache iceberg source code analysis: schema evolution
- Intelligent operation and maintenance practice: banking business process and single transaction tracking
- PIP version problems: PIP problems still occur when installing akshare and using Tsinghua source and Douban source
- [C supplement] [string] display the schedule of a month by date
- Session layer of csframework, server and client (1)
- People help ant help task platform repair source code
- Gold, silver and four job hopping, interview questions are prepared, and Ali becomes the champion
猜你喜欢

Record 3 - the state machine realizes key control and measures the number of external pulses

People help ant help task platform repair source code

Definition of rotation axis in mujoco

Common design parameters of solid rocket motor

Thinkphp6 - CMS multi wechat management system source code

How to use JMeter function and mockjs function in metersphere interface test

This is the latest opportunity of the London bank trend

Review Net 20th anniversary development and 51aspx growth

Rotation order and universal lock of unity panel

Nearly 60% of the employees strongly support Ctrip's "3+2" working mode, and work at home for two days a week
随机推荐
Sword finger offer II 105 Maximum area of the island
Domestic spot silver should be understood
February 16, 2022 Daily: graph neural network self training method under distribution and migration
The latest intelligent factory MES management system software solution
Glidefast consulting was selected as the elite partner of servicenow in 2022
Good looking UI mall source code has been scanned, no back door, no encryption
Detailed explanation of select in golang
Redis主从实现10秒检查与恢复
Penetration practice vulnhub range Keyring
Check log4j problems using stain analysis
Apk signature process introduction [easy to understand]
The difference and relationship between iteratible objects, iterators and generators
MySQL + JSON = King fried
Is Huishang futures a regular futures platform? Is it safe to open an account in Huishang futures?
Record 3 - the state machine realizes key control and measures the number of external pulses
At present, where is the most formal and safe account opening for futures speculation? How to open a futures account?
Is the software of futures pioneer formal and safe? Which futures company is safer to choose?
Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse
MES production equipment manufacturing execution system software
Quick foundation of group theory (5): generators, Kelley graphs, orbits, cyclic graphs, and "dimensions" of groups?