在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given an array of integers Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Example 2: Input: arr = [1,2] Output: false Example 3: Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] Output: true
Constraints:
给你一个整数数组 如果每个数的出现次数都是独一无二的,就返回
示例 1: 输入:arr = [1,2,2,1,1,3] 输出:true 解释:在该数组中,1 出现了 3 次,2 出现了 2 次,3 只出现了 1 次。没有两个数的出现次数相同。 示例 2: 输入:arr = [1,2] 输出:false 示例 3: 输入:arr = [-3,0,1,-3,1,1,1,-3,10,0] 输出:true
提示:
Runtime: 12 ms
Memory Usage: 20.7 MB
1 class Solution { 2 func uniqueOccurrences(_ arr: [Int]) -> Bool { 3 var freq:[Int:Int] = [Int:Int]() 4 for x in arr 5 { 6 freq[x,default:0] += 1 7 } 8 var occur:Set<Int> = Set<Int>() 9 for (key,val) in freq 10 { 11 if occur.contains(val) 12 { 13 return false 14 } 15 occur.insert(val) 16 } 17 return true 18 } 19 } 12ms 1 class Solution { 2 func uniqueOccurrences(_ arr: [Int]) -> Bool { 3 var uniqueDic: [Int: Int] = [:] 4 var occurArr = [Int]() 5 for num in arr { 6 if let occurNum = uniqueDic[num] { 7 uniqueDic[num]! = occurNum + 1 8 } else { 9 uniqueDic[num] = 1 10 } 11 } 12 for (_, value) in uniqueDic { 13 if occurArr.contains(value) { 14 return false 15 } 16 occurArr.append(value) 17 } 18 return true 19 20 } 21 }
20ms
1 class Solution { 2 func uniqueOccurrences(_ arr: [Int]) -> Bool { 3 var subArray = arr 4 var count = arr.count 5 var chkCount = count 6 var boolArray = Array(repeating: false, count: count) 7 8 for i in arr { 9 subArray.removeAll() { $0 == i } 10 count = subArray.count 11 12 if chkCount > count { 13 if boolArray[chkCount - count] == true { 14 return false 15 } 16 boolArray[chkCount - count] = true 17 chkCount = count 18 } 19 } 20 return true 21 } 22 }
|
请发表评论