当前位置:网站首页>[leetcode]75. color classification - problem solving (execution time beat 90%, memory consumption beat 78%)
[leetcode]75. color classification - problem solving (execution time beat 90%, memory consumption beat 78%)
2022-07-24 16:23:00 【User 6557940】
01
Title Description
Give one that contains red 、 White and blue , altogether n Array of elements , Sort them in place , Make elements of the same color adjacent , And follow the red 、 white 、 In blue order . In this question , We use integers 0、 1 and 2 Red... Respectively 、 White and blue .
Be careful : You can't use the sort function in the code base to solve this problem .
Example :
Input : [2,0,2,1,1,0]
Output : [0,0,1,1,2,2]
02
analysis
obviously , The most intuitive method is to count through one-time traversal 0、1、2 The number of , Again according to 0、1、2 Rewrite the array in the order of . But this method requires two scans . Is there a way to complete the arrangement by one scan ? The answer is : Yes !
problem 1: What's the idea ?
Observe the output of the topic description and topic examples ,0 At the top of the sequence ,2 At the bottom of the list , therefore , When scanning an array , We can judge the value of the current number :
- If it is 0, Just move to the front of the sequence ;
- If it is 2, Just move to the back of the sequence .
problem 2: How to move forward and backward ?
At this point, another question is thrown : Move forward , Where to move ? Move back , And where to move ?
—— Set two markers flag0 and flag2.
At first, we didn't know how many there would be in the end 0, But the front of the sequence must be 0, therefore flag0 The initial value is the top of the sequence , namely 0; Again , At the beginning, we didn't know how many there were in the end 2, But the last part of the sequence must be 2, therefore flag2 The initial value is the index position of the last element of the array . After initialization , Next, start the scanning process ( That is, update the tag flag0 and flag2 The process of ):
- If the current element is 0, Index the current element to flag0 The element exchange position of ,flag0++;
- If the current element is 2, Index the current element to flag2 The element exchange position of ,flag2--.
problem 3: If there is no 0 Or not 2 Well ?
If there is no 0, that flag0 Always point to the first position of the array ; Empathy , If there is no 2,flag2 Always index the position of the last element of the array .
problem 4: If the current element is 1, How to deal with ?
Don't deal with ! Why not deal with it ? Just because there are two marks flag0 and flag2 The existence of , Because the two tags strictly limit 0 and 2 The boundary of the , Naturally , Between the two boundaries is 1 了 .
03
Code
void swap(vector<int>& nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
void sortColors(vector<int>& nums) {
// Initialization tag
int flag0 = 0;
int flag2 = nums.size() - 1;
for (int i = 0; i <= flag2; i++){
if (nums[i] == 2){
swap(nums, i, flag2);
flag2--;
i--;// Why i--, Because of the exchange to i The value at may be 0
}
else if (nums[i] == 0){
swap(nums, i, flag0);
flag0++;
}
}
}04
Execution results
边栏推荐
- Scala functions and their higher-order applications
- PHP中array_merge的坑
- leetcode:162. 寻找峰值【二分寻找峰值】
- 普林斯顿微积分读本02第一章--函数的复合、奇偶函数、函数图像
- Telephone system rules
- Using native JS to realize magnifying glass function
- The 3D sensing market is accelerating. Who will be better, TOF or structured light?
- Code shoe set - mt2095 · zigzag jump
- Codeforces round 690 (Div. 3) B. last year's substring conventional solution
- Using JS to implement click events
猜你喜欢

机器学习笔记 - 构建推荐系统(5) 前馈神经网络用于协同过滤
[email protected]"/>ZBar source code analysis - img_ scanner. c | [email protected]

20. Shell programming variables

Machine learning notes - building a recommendation system (5) feedforward neural network for collaborative filtering

Complete guide on how to prevent cross site scripting (XSS) attacks

Urban safety series popular science - enter the high incidence period of drowning, if you know the common sense of life-saving

Custom view - Custom button

How vscode mouse wheel enlarges the interface

Talk about C pointer

C TCP client form application asynchronous receiving mode
随机推荐
Wentai technology's revenue in the first quarter soared by 184.6% year-on-year, and its net profit soared by 256.21%!
ZBar source code analysis - img_ scanner. c | [email protected]
You really should go to the factory to move bricks!
How to realize seamless rotation map? Write it again with native JS
Introduction to bermudagrass
torch_ How to use scatter. Scatter() in detail
2.19 haas506 2.0开发教程 - bluetooth - 蓝牙通信(仅支持2.2以上版本)
Will the capital market be optimistic about TCL's folding screen story?
“天上天下,唯我独尊”——单例模式
Knowledge points of MySQL (12)
收益率在百分之六以上的理财产品,请说一下
【南京农业大学】考研初试复试资料分享
双指针滑动窗口法解析及LeetCode相关题解
About SQL data query statements
若依 this.$router.push 同地址不同参,页面不刷新问题
There are more than 20 categories of the four operators in MySQL. It took three days and three nights to sort them out. Don't collect them quickly
Please talk about the financial products with a yield of more than 6%
After taking aiyouteng's medicine, Naifei's condition improved
Dynamics 365: how to get the threshold value of executemullerequest in batch requests
By default, the select drop-down box selects the solution ligerui that the selected attribute does not work