Most Common Elements in an Array using Swift - iOS Coding Challenge
Complexity : O(n)
Let's Code :
//: Playground - noun: a place where people can play
import Foundation
import UIKit
var elementArray : [String] = ["one","two","three","four","five","two","five","two","one","two","five","three","three","four","one","four","three","five"]
func getMostCommonElementFromArray(array:[String]) -> [String] {
var mostOccuredElements : [String] = []
var elementDict : [String:Int] = [:]
for item in array {
if let count = elementDict[item] {
elementDict[item] = count + 1
}else{
elementDict[item] = 1
}
}
let highestVal = elementDict.values.max()
for (element,_) in elementDict {
if elementDict[element] == highestVal {
mostOccuredElements.append(element)
}
}
return mostOccuredElements
}
getMostCommonElementFromArray(array: elementArray)
//: Playground - noun: a place where people can play
import Foundation
import UIKit
var elementArray : [String] = ["one","two","three","four","five","two","five","two","one","two","five","three","three","four","one","four","three","five"]
func getMostCommonElementFromArray(array:[String]) -> [String] {
var mostOccuredElements : [String] = []
var elementDict : [String:Int] = [:]
for item in array {
if let count = elementDict[item] {
elementDict[item] = count + 1
}else{
elementDict[item] = 1
}
}
let highestVal = elementDict.values.max()
for (element,_) in elementDict {
if elementDict[element] == highestVal {
mostOccuredElements.append(element)
}
}
return mostOccuredElements
}
getMostCommonElementFromArray(array: elementArray)

Comments
Post a Comment