如何在Swift中查找Array的每个元素的频率

时间:2016-12-06 09:08:01

标签: arrays swift

输入:1 3 4 2 3 1

输出:

元素1:计数2

元素3:计数2

元素4:计数1

元素2:计数1

var count:Int
let tempArray = [1, 1,1, 4 ,1]
var index  = 0
var fequency = [Int]()
for m in 0 ..< tempArray.count{
  fequency.append(-1)
}
print(fequency)
for i in 0 ..< tempArray.count{
  count = 1
  for j in i + 1  ..< tempArray.count{
    index = j
    if tempArray[i] == tempArray[j]{
      count = count + 1
   fequency [j] = 0
      print(fequency)
  }
    if fequency[i] != 0 {
        fequency[i] = count
     // print("frequency->",fequency)
    }

}
  print("\(tempArray[i]) occures at \(fequency[i]) times")

}

0 个答案:

没有答案