Java&Go-LeetCode922. 按奇偶排序数组 II-双指针
- 算法
- 1.双指针
- 2.一个指针在奇数位置上移动,一个指针在偶数位置上移动
- 3.每次移动到奇数位置上是偶数,偶数位置上是奇数,交换二者,继续移动
public int[] sortArrayByParityII(int[] A) { int n = A.length; int i = 0, j = 1; while (i < n && j < n) { while (i < n && (A[i] & 1) == 0) { i += 2; } while (j < n && (A[j] & 1) == 1) { j += 2; } if (i < n && j < n) { swap(A, i, j); } i += 2; j += 2; } return A; } private void swap(int[] A, int x, int y) { int temp = A[x]; A[x] = A[y]; A[y] = temp; }
func sortArrayByParityII(A []int) []int { n := len(A) i, j := 0, 1 for i < n && j < n { for i < n && (A[i] & 1) == 0 { i += 2 } for j < n && (A[j] & 1) == 1 { j += 2 } if i < n && j < n { A[i], A[j] = A[j], A[i] } i, j = i + 2, j + 2 } return A }
- 算法
- 1.奇数位置上放上奇数时,偶数位置上自动放好偶数
- 2.每次循环,一直和偶数位置上的数交换,直到该奇数位置上奇数为止
public int[] sortArrayByParityII(int[] A) { int n = A.length; int even = 0, odd = 1; for (; even < n && odd < n; odd += 2) { while ((A[odd] & 1) == 0) { int temp = A[even]; A[even] = A[odd]; A[odd] = temp; even += 2; } } return A; }
func sortArrayByParityII(A []int) []int { n := len(A) even, odd := 0, 1 for ; even < n && odd < n; odd += 2 { for (A[odd] & 1) == 0 { A[even], A[odd] = A[odd], A[even] even += 2 } } return A }
LeetCode题解 文章被收录于专栏
测试