题解 | #牛的品种排序I#
牛的品种排序I
https://www.nowcoder.com/practice/e3864ed7689d460c9e2da77e1c866dce
知识点:数组,排序
题目要求将0排列在数组左边,将1排列在数组右边,我们可以遍历一次原数组,找出0的个数,之后,将剩余位置全部补1,得到结果数组。
Java题解如下
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型一维数组
* @return int整型一维数组
*/
public int[] sortCows (int[] cows) {
// write code here
int n = cows.length;
int[] res = new int[n];
int j = 0;
for(int i = 0; i < n; i++) {
if(cows[i] == 0) {
res[j++] = 0;
}
}
while(j < n) {
res[j++] = 1;
}
return res;
}
}
查看22道真题和解析

