题解 | #牛的品种排序II#
牛的品种排序II
https://www.nowcoder.com/practice/43e49fbb98b4497ba46e185918188b1c
# 两种思路,如下:
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param cows int整型一维数组
# @return int整型一维数组
#
class Solution:
def sortCows(self , cows: List[int]) -> List[int]:
# write code here
# 建立一个新数组来存放排序结果
# 遍历数组,如果遇到0则插入队首,遇到2则插入队尾,否则在中间找到正确的位置放1
# result = []
# for cow in cows:
# if cow == 0:
# result.insert(0, cow)
# elif cow == 2:
# result.append(cow)
# else:
# i = 0
# while result[i] == 0:
# i += 1
# if i == len(result):
# break
# result.insert(i, cow)
# return result
# 还有一个暴力的办法,用三个数组,一个存0,一个存1,一个存2,最后把它们拼起来
result_0, result_1, result_2 = [], [], []
for cow in cows:
if cow == 0:
result_0.append(cow)
elif cow == 1:
result_1.append(cow)
else:
result_2.append(cow)
return result_0 + result_1 + result_2
查看15道真题和解析