题解 | #牛的品种排序I#
牛的品种排序I
https://www.nowcoder.com/practice/e3864ed7689d460c9e2da77e1c866dce
知识点
数组
解题思路
创建一个ans存储最总的结果,用一个end表示下一个1需要放置的下标,遍历num,如果遇到1就把1放到ans的[end]处;如果遇到0不必处理,因为数组默认值就是0。
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 end = n - 1; int[] ans = new int[n]; for (int cow : cows) { if(cow == 1){ ans[end --] = 1; } } return ans; } }