パリティにより、905ソート配列
アレイ所定の A
非負整数の、すべての偶数の要素からなる配列を返す A
のすべての奇数の要素が続くが、 A
。
あなたはこの条件を満たすすべての回答の配列を返すことがあります。
例1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
注意:
1 <= A.length <= 5000
0 <= A[i] <= 5000
時間制限を超え:
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
for(int i = 0; i < A.size(); )
{
if(A[i]%2 == 1)
{
A.push_back(A[i]);
A.erase(A.begin()+i);
}
else
i++;
}
return A;
}
};
スローバージョン:
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
vector<int> even;
vector<int> odd;
for(int i = 0; i < A.size();i++)
{
if(A[i]%2 == 1)
odd.push_back(A[i]);
else
even.push_back(A[i]);
}
A.erase(A.begin(), A.end());
A.insert(A.end(), even.begin(), even.end());
A.insert(A.end(), odd.begin(), odd.end());
return A;
}
};
:パーティションを()を使用して、
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
partition(A.begin(), A.end(), [](int i){return i%2==0;});
return A;
}
};
パフォーマンス:
並べ替えを使用して高速化バージョン():
class Solution {
public:
vector<int> sortArrayByParity(vector<int>& A) {
sort(A.begin(), A.end(), [](int lhs, int rhs) {
if (lhs % 2 == 1 && rhs % 2 == 0) {
return false; // left is odd, right is even, out of order
} else if (rhs % 2 == 1 && lhs % 2 == 0) {
return true; // left is even, right is odd, OK
} else {
return false;
}
});
return A;
}
};
便利な知識:
ソート配列の977乗
整数の配列を指定は A
また、ソートされた非減少順に、各番号の正方形の配列を返し、非減少順にソート。
例1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
注意:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A
非減少順にソートされます。
スローバージョン:
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
for(int i = 0; i < A.size(); i++)
A[i] = A[i]*A[i];
sort(A.begin(), A.end());
return A;
}
};
パフォーマンス:
二つのポインタ:
class Solution {
public:
vector<int> sortedSquares(vector<int>& A) {
int p1 = 0; int p2 = A.size()-1;
vector<int> v(A.size());
for(int i = A.size()-1; i >= 0; i--)
{
if(A[p1]<0 && abs(A[p1]) > A[p2]) //First error: A[p1] compares with A[p2] not with A[i]
{
v[i] = A[p1]*A[p1];
p1++;
}
else
{
v[i] = A[p2]*A[p2];
p2--;
}
}
return v;
}
};
パフォーマンス:
団体客の830ポジション
文字列では S
小文字の、これらの文字は、同じ文字の連続するグループを形成します。
例えば、のような文字列は、 S = "abbxxxxzyy"
グループを持っている "a"
、 "bb"
、 "xxxx"
、 "z"
と "yy"
。
グループコール 大を 、それは3文字以上を持っている場合。私たちは、すべての大規模なグループの開始と終了位置をしたいと思います。
最終的な答えは、辞書式順序にする必要があります。
例1:
入力: "abbxxxxzzy"
出力:[[3,6]]
説明:"xxxx" is the single
3を起動し、位置6を終了すると大規模なグループ。
注意: 1 <= S.length <= 1000
スローバージョン:
class Solution {
public:
vector<vector<int>> largeGroupPositions(string S) {
vector<vector<int>> ans;
int start = 0; int end = 0;
S = S + '#'; //in order to avoid S[i+1] being out of array index
for(int i = 0; i < S.length()-1; i++)
{
if(end - start >= 2 && S[i] != S[i+1])
{
ans.push_back({start, end});
}
if(S[i]!=S[i+1])
{
start = end = i+1;
}
else
end++;
}
return ans;
}
};
パフォーマンス:
便利な知識: