法一:对数组进行排序,将所有的偶数放到奇数的前面,我们可以考虑使用两个for循环,先将所有的偶数存到数组中,在将所有的奇数存进去
class Solution {
public int[] sortArrayByParity(int[] A) {
int[] B = new int[A.length];
int t = 0;
for(int i = 0;i<A.length;i++){
if(A[i]%2 == 0)
B[t++] = A[i];
}
for(int i = 0;i<A.length;i++){
if(A[i]%2 != 0)
B[t++] = A[i];
}
return B;
}
}
法二:通过比较器对数组进行排序
class Solution {
public int[] sortArrayByParity(int[] A) {
Integer[] B = new Integer[A.length];
for (int t = 0; t < A.length; ++t)
B[t] = A[t];
Arrays.sort(B, (a, b) -> Integer.compare(a%2, b%2));
for (int t = 0; t < A.length; ++t)
A[t] = B[t];
return A;
/* Alternative:
return Arrays.stream(A)
.boxed()
.sorted((a, b) -> Integer.compare(a%2, b%2))
.mapToInt(i -> i)
.toArray();
*/
}
}
最后
以上就是真实钢笔最近收集整理的关于leetcode-905-数组排序的全部内容,更多相关leetcode-905-数组排序内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复