gpt4 book ai didi

scala - 将零移至数组末尾

转载 作者:行者123 更新时间:2023-12-02 19:22:36 26 4
gpt4 key购买 nike

我正在尝试解决 scala 中的以下问题

Input:[1,0,44,55,0,43,78,99]
output:[1,44,55,43,78,99,0,0]

这是我尝试过的

def moveZeros(nums:Array[Int]): Array[Int] ={
for(i<-0 until nums.length ; j<-0 until nums.length){
if(nums(j)!=0)
{
var temp:Int = nums(i)
nums(i)=nums(j)
nums(j)=temp
}

}
nums
}

输出:[0,0,1,44,55,78,99,43]

非预期输出

我正在寻找 O(n) 时间复杂度和 O(1) 空间复杂度解决方案

这是一个leetcode问题 https://leetcode.com/problems/move-zeroes/

最佳答案

你可以尝试这样的事情:

nums.zipWithIndex
.sortBy(t => if (t._1 == 0) Int.MaxValue else t._2)
.map(_._1)

zipWithIndex会将您的集合映射到元素值及其索引的元组序列中(即 [(1, 0), (0, 21), (44, 2)] 作为示例数组的开头)

sortBy 将按元素索引或 Int.MaxValue

执行排序

map 会将 map 返回到原始元素。

关于scala - 将零移至数组末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62853689/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com