题解 | #牛的品种排序I#
牛的品种排序I
https://www.nowcoder.com/practice/e3864ed7689d460c9e2da77e1c866dce
题目考察的知识点:数组
题目解答方法的文字分析:使用双指针,左边找1,右边找0,交换位置即可
本题解析所用的编程语言:java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型一维数组
* @return int整型一维数组
*/
public int[] sortCows (int[] cows) {
// write code here
int length = cows.length;
if (length == 0) return new int[0];
int i = 0, j = length - 1;
int temp;
while (i < j) {
while (i<length && cows[i] == 0) i++;
while (j<length && cows[j] == 1) j--;
if (i < j) {
temp = cows[i];
cows[i] = cows[j];
cows[j] = temp;
}
}
return cows;
}
}