当前位置:网站首页>Leetcode skimming ---75
Leetcode skimming ---75
2022-07-03 10:35:00 【Long time no see 0327】
subject : Give one that contains red 、 White and blue 、 common n Array of elements nums , Sort them in place , Make elements of the same color adjacent , And follow the red 、 white 、 In blue order . We use integers 0、 1 and 2 Red... Respectively 、 White and blue . Must be in a library that does not use sort Function to solve this problem .
Input :nums = [2,0,2,1,1,0]
Output :[0,0,1,1,2,2]
Method 1 : Single pointer
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
int ptr = 0;
for (int i = 0; i < n; ++i) {
if (nums[i] == 0) {
swap(nums[i], nums[ptr]);
++ptr;
}
}
for (int i = ptr; i < n; ++i) {
if (nums[i] == 1) {
swap(nums[i], nums[ptr]);
++ptr;
}
}
}
};Complexity analysis
Time complexity :O(n)
Spatial complexity :O(1)
Method 2 : Double pointer
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
int p0 = 0, p1 = 0;
for (int i = 0; i < n; ++i) {
if (nums[i] == 1) {
swap(nums[i], nums[p1]);
++p1;
} else if (nums[i] == 0) {
swap(nums[i], nums[p0]);
if (p0 < p1) {
swap(nums[i], nums[p1]);
}
++p0;
++p1;
}
}
}
};Complexity analysis
Time complexity :O(n)
Spatial complexity :O(1)
Method 3 : Double pointer two
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
int p0 = 0, p2 = n - 1;
for (int i = 0; i < n; ++i) {
while (i <= p2 && nums[i] == 2) {
swap(nums[i], nums[p2]);
--p2;
}
if (nums[i] == 0) {
swap(nums[i], nums[p0]);
++p0;
}
}
}
};Complexity analysis
Time complexity :O(n)
Spatial complexity :O(1)
边栏推荐
猜你喜欢
随机推荐
mysql5.7安装和配置教程(图文超详细版)
Model evaluation and selection
神经网络入门之模型选择(PyTorch)
Powshell's set location: unable to find a solution to the problem of accepting actual parameters
20220605 Mathematics: divide two numbers
2-program logic
神经网络入门之预备知识(PyTorch)
Ut2016 learning notes
Leetcode - the k-th element in 703 data flow (design priority queue)
3.3 Monte Carlo Methods: case study: Blackjack of Policy Improvement of on- & off-policy Evaluation
Hands on deep learning pytorch version exercise solution - 2.3 linear algebra
Simple real-time gesture recognition based on OpenCV (including code)
Knowledge map reasoning -- hybrid neural network and distributed representation reasoning
Step 1: teach you to trace the IP address of [phishing email]
Ind FXL first week
CSDN, I'm coming!
Ind yff first week
『快速入门electron』之实现窗口拖拽
20220603 Mathematics: pow (x, n)
Leetcode刷题---202









