经典题目:
给定一个非负整数数组 A,返回一个数组,在该数组中, A 的所有偶数元素之后跟着所有奇数元素。
你可以返回满足此条件的任何数组作为答案。
主要要掌握最优解 这道题很简单
类快排(你不是真正的快排~)
/** * Note: The returned array must be malloced, assume caller calls free(). */ void swap(int *a,int *b) { int t = *a; *a = *b; *b = t; } int* sortArrayByParity(int* nums, int numsSize, int* returnSize){ //kuaipaima *returnSize = numsSize; int i,j; for(i = 0,j = numsSize-1;i < j;) { if(nums[i]%2 == 0) { i++; } if(nums[j]%2 == 1) { j--; } if(i > j) break; swap(&nums[i],&nums[j]); } return nums; }
官方答案
class Solution { public int[] sortArrayByParity(int[] A) { int i = 0, j = A.length - 1; while (i < j) { if (A[i] % 2 > A[j] % 2) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } if (A[i] % 2 == 0) i++; if (A[j] % 2 == 1) j--; } return A; } } 作者:LeetCode 链接:https://leetcode-cn.com/problems/sort-array-by-parity/solution/an-qi-ou-pai-xu-shu-zu-by-leetcode/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。