Advertisement
Alexxik

Untitled

Mar 19th, 2024
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.05 KB | None | 0 0
  1. // Найти К максимальных элементов
  2.  
  3. func kMostLargest(_ numbers: [Int], k: Int) {
  4.    
  5.     var max = numbers.max()!
  6.     var indexMax = numbers.firstIndex(of: max)! as Int
  7.    
  8.     var result = [max]
  9.     var i = 0
  10.    
  11.     var currentMax = -Int.max
  12.     var currentMaxIndex = -1
  13.    
  14.     var sameMaxIsFound = false
  15.    
  16.     while i < numbers.count && result.count < k {
  17.  
  18.         while i < numbers.count {
  19.             if numbers[i] > currentMax && numbers[i] < max {
  20.                 print(numbers[i])
  21.                 currentMax = numbers[i]
  22.                 currentMaxIndex = i
  23.             }
  24.             if numbers[i] == max && i > indexMax {
  25.                 currentMax = numbers[i]
  26.                 currentMaxIndex = i
  27.                 break
  28.             }
  29.             i += 1
  30.         }
  31.         result.append(currentMax)
  32.         indexMax = currentMaxIndex
  33.         max = currentMax
  34.         i = 0
  35.         currentMax = numbers[i]
  36.     }
  37.     print(result)
  38. }
  39.  
  40. kMostLargest([10, 5, 8, 6, 8, 8, 8, 7, 7, 7, 7, 8, 9, 9], k: 5)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement