题解 | #牛的品种排序I#
牛的品种排序I
https://www.nowcoder.com/practice/e3864ed7689d460c9e2da77e1c866dce
知识点:双指针 头尾指针
思路:最好的解法,时间和空间复杂度达到完美
这题可以使用头尾指针:尾指针从尾部出发,填充1,头指针从头出发,填充0
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param cows int整型一维数组
* @return int整型一维数组
*/
public int[] sortCows (int[] cows) {
// write code here
int head = 0, tail = cows.length-1;
while (tail >= 0) {
//尾部指针找1
if (tail>=0 && cows[tail] == 0) {
//和头指针交换1
//头尾不用相遇
while (head < cows.length && head<tail) {
if (head < cows.length && cows[head] == 1 ) {
cows[tail] = 1;
cows[head] = 0;
break;
}
head++;
}
}
tail--;
}
return cows;
}
}

