题解 | #牛的品种排序II#
牛的品种排序II
https://www.nowcoder.com/practice/43e49fbb98b4497ba46e185918188b1c
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型一维数组
* @return int整型一维数组
*/
public int[] sortCows (int[] cows) {
// write code here
int left = 0;
int right = cows.length - 1;
while (left < cows.length) {
while (left < right && cows[left] == 0 ) {
left++;
}
while (left < right && cows[right] != 0) {
right--;
}
if (left < right) {
int tmp = cows[left];
cows[left] = cows[right];
cows[right] = tmp;
}
left++;
right--;
}
left = 0;
right = cows.length - 1;
while (left < cows.length && cows[left] == 0) {
left++;
}
while (left < cows.length) {
while (left < right && cows[left] == 1 ) {
left++;
}
while (left < right && cows[right] != 1) {
right--;
}
if (left < right) {
int tmp = cows[left];
cows[left] = cows[right];
cows[right] = tmp;
}
left++;
right--;
}
return cows;
}
}

查看14道真题和解析