在int swift数组中找出最大的三个数字

qaxu7uf2  于 2023-11-16  发布在  Swift
关注(0)|答案(5)|浏览(155)

我试图在int数组中找到最大的三个数字,但我的算法返回错误的结果
输入和输出largestthreeNumbers([141,1,17,-7,-17,-27,18,541,8,7,7])
结果[141,1,17,18,541]预期结果[141,18,541]

func largestthreeNumbers(_ array:[Int]) ->[Int]{
        var first = 0
        var second = 0
        var thrid = 0
        var result = [Int]()
        if array.count < 3 {
            print("Invalid Input")
            return result
        }
        
        for i in 0 ..< array.count {
            if array[i] > first{
                thrid = second
                second = first
                first = array[i]
                result.append(first)
               
            }
            else if(array[i] > second){
                thrid = second
                second = array[i]
                result.append(second)
               
                
            }
            else if (array[i] > thrid){
                thrid = array[i]
                result.append(thrid)
           
            }
        }
        
        return result
    }

字符串

oalqel3c

oalqel3c1#

如果你需要保留元素的顺序,你可以通过它的值对集合元素索引进行排序,得到最高元素的最后3个索引,对它们进行排序并Map相应的元素:

let numbers = [141, 1, 17, -7, -17, -27, 18, 541, 8, 7, 7]

let largestNumbers = numbers
    .indices
    .sorted { numbers[$0]<numbers[$1] }
    .suffix(3)
    .sorted()
    .map{ numbers[$0] }  // [141, 18, 541]

字符串
如果结果的顺序不重要,你可以简单地按降序对元素进行排序,得到前n个元素:

let largestNumbers = numbers.sorted(by: >).prefix(3)   // [541, 141, 18]


如果你正在处理一个大的集合,你可以在GitHub上从Apple的swift-algorithms中检查SortedPrefix算法,就像在这篇关于如何在Swift字典中获得前3个最大值的SO文章中提到的那样。

epfja78i

epfja78i2#

每次你发现firstsecondthrid的新的最大值时,你都在循环中附加到result上。这可能会发生3次以上。但是所需的数组只包含3个元素。显然,你不应该在循环中添加result
你应该只在循环结束时向result追加值firstsecondthrid。你也可以直接返回数组文字[first, second, thrid]

func largestThreeNumbers(_ array: [Int]) -> [Int] {
    var first = 0
    var second = 0
    var third = 0
    if array.count < 3 {
        print("Invalid Input")
        return []
    }
    
    for element in array {
        if element > first{
            third = second
            second = first
            first = element
           
        }
        else if element > second {
            third = second
            second = element
           
            
        }
        else if element > third {
            thrid = element
       
        }
    }
    return [first, second, third]
}

字符串

kzipqqlq

kzipqqlq3#

我是这样做的,深受Sweeper方法的启发,但是构建的方式可以让你在将来添加一个优先级队列数据结构,当一个数据结构最终(希望)被添加到标准库中时。

struct PriorityQueueOf3<T: Comparable> {
    public private(set) var values: (T, T, T) // Ordered largest to smallest
    
    mutating func insert(_ newValue: T) {
        if newValue > values.0      { (values.0, values.1, values.2) = (newValue, values.0, values.1) }
        else if newValue > values.1 { (values.0, values.1, values.2) = (values.0, newValue, values.1) }
        else if newValue > values.2 { (values.0, values.1, values.2) = (values.0, values.1, newValue) }
    }
    
    func toArray() -> [T] {
        [values.0, values.1, values.2]
    }
}

func largestThreeNumbers(_ array: [Int]) -> [Int] {
    if array.count < 3 {
        fatalError("Invalid Input") // TODO: Handle this error better
    }
    
    var queue = PriorityQueueOf3<Int>(values: (0, 0, 0))
    
    for element in array {
        queue.insert(element)
    }
    
    return queue.toArray()
}

let input = Array(1...10).shuffled()
let result = largestThreeNumbers(input)
print(result)

字符串
如果你想保留初始排序,你可以这样做:

struct IndexedValue<T: Comparable>: Comparable {
    let index: Int
    let value: T
    
    static func == (lhs: IndexedValue, rhs: IndexedValue) -> Bool { lhs.value == rhs.value }
    static func <  (lhs: IndexedValue, rhs: IndexedValue) -> Bool { lhs.value <  rhs.value }
}

func largestThreeNumbers(_ array: [Int]) -> [Int] {
    if array.count < 3 {
        fatalError("Invalid Input") // TODO: Handle this error better
    }
    
    let dummy = IndexedValue(index: 0, value: 0)
    var queue = PriorityQueueOf3(values: (dummy, dummy, dummy))
    
    for (element, index) in zip(array, array.indices) {
        queue.insert(IndexedValue(index: index, value: element))
    }
    
    return queue.toArray()
        .sorted(by: { $0.index < $1.index }) // restore the original ordering
        .map(\.value) // discard the indices
}

let input = Array(1...10).shuffled()
let result = largestThreeNumbers(input)

print(input)
print(result)


这确实是对大型数据集的优化,但它并不是很实用。一个简单的排序是O(log(n) * n),而这只是O(n)。你需要一个非常大的输入来使它值得复杂。

3lxsmp7m

3lxsmp7m4#

var numberArray  = [5,2,3,1,7,4,6]
var firstLargest = numberArray[0]
var secondLargest = numberArray[0]
var thirdLargest = numberArray[0]
var result = [Int]()

for i in numberArray {
    if firstLargest < i {
        firstLargest = i
    }
}
result.append(firstLargest)

for j in numberArray {
    if j != firstLargest && secondLargest < j {
        secondLargest = j
    }
}
result.append(secondLargest)

for k in numberArray {
    if k != firstLargest && k != secondLargest && thirdLargest < k {
        thirdLargest = k
    }
}
result.append(thirdLargest)
print(result)

字符串

nlejzf6q

nlejzf6q5#

在Java中

public class Test {

public static void main(String[] args) throws Exception{
 
 int[] arr={7,18,92,72,29,57};
 
 int first,second,third;
 
 first=second=third=Integer.MIN_VALUE;
 
 for(int i=0;i<arr.length;i++){
   if(arr[i]>first){
     third=second;
     second=first;
     first=arr[i];
   }else if(arr[i]>second){
     third=second;
     second=arr[i];
     
   }else{
     third=arr[i];
   }
 }
 System.out.println(""+first+"\t"+second+"\t"+third);

}

字符串
}

相关问题