leetCode中怎么按奇偶排序數組,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
給定一個非負整數數組 A, A 中一半整數是奇數,一半整數是偶數。
對數組進行排序,以便當 A[i] 為奇數時,i 也是奇數;當 A[i] 為偶數時, i 也是偶數。
你可以返回任何滿足上述條件的數組作為答案。
示例:
輸入:[4,2,5,7]
輸出:[4,5,2,7]
解釋:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也會被接受。
提示:
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
根據數組的索引位置進行操作
public class SortArrayByParityIITest {
public static void main(String[] args) {
int[] array = {4, 2, 5, 7};
int[] result = sortArrayByParityII(array);
for (int num : result) {
System.out.print(num + "\t");
}
}
public static int[] sortArrayByParityII(int[] A) {
int[] result = new int[A.length];
if (A == null || A.length == 0) {
return result;
}
int index = 0;
for (int i = 0; i < A.length; i++) {
if (A[i] % 2 == 0) {
result[index] = A[i];
index += 2;
}
}
index = 1;
for (int i = 0; i < A.length; i++) {
if (A[i] % 2 != 0) {
result[index] = A[i];
index += 2;
}
}
return result;
}
}
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。