leetcode (Sort Array By Parity II)
程序员文章站
2022-07-15 09:37:56
...
Title:Sort Array By Parity II 922
Difficulty:Easy
原题leetcode地址:https://leetcode.com/problems/sort-array-by-parity-ii/
1. 双指针
时间复杂度:O(n),一次一层while循环,需要遍历整个数组。
空间复杂度:O(1),没有申请额外空间。
/**
* 双指针
* @param A
* @return
*/
public static int[] sortArrayByParityII(int[] A) {
int beginIndex = 0;
int endIndex = A.length - 1;
while (beginIndex <= A.length - 1 && endIndex >= 1) {
if (A[beginIndex] % 2 == 1 && A[endIndex] % 2 == 0) {
A[beginIndex] = A[beginIndex] + A[endIndex];
A[endIndex] = A[beginIndex] - A[endIndex];
A[beginIndex] = A[beginIndex] - A[endIndex];
beginIndex += 2;
endIndex -= 2;
}
else if (A[beginIndex] % 2 == 1 && A[endIndex] % 2 == 1) {
endIndex -= 2;
}
else if (A[beginIndex] % 2 == 0 && A[endIndex] % 2 == 0) {
beginIndex += 2;
}
else if (A[beginIndex] % 2 == 0 && A[endIndex] % 2 == 1) {
beginIndex += 2;
endIndex -= 2;
}
}
return A;
}
上一篇: c 十进制转二进制
推荐阅读
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
LeetCode 33. Search in Rotated Sorted Array && 81. Search in Rotated Sorted Array II
-
LeetCode C++ 454. 4Sum II【Hash Table/Sort/Two Pointers/Binary Search】
-
leetcode (Sort Array By Parity II)
-
leetcode (Sort Array By Parity)
-
LeetCode 167 Two Sum II - Input array is sorted(左右指针)
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
【LeetCode】80. Remove Duplicates from Sorted Array II (删除排序数组中的重复项 II)-C++实现及详细图解
-
LeetCode--删除排序数组中的重复项 II (Remove Duplicates from Sorted Array II ) ( C语言版 )
-
905. Sort Array By Parity(按奇偶排序数组)