在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ A zero-indexed array A of length N contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], ... } subjected to the rule below. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]]… By that analogy, we stop adding right before a duplicate element occurs in S. Example 1: Input: A = [5,4,0,3,1,6,2] Output: 4 Explanation: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. One of the longest S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} Note:
索引从 假设选择索引为 示例 1: 输入: A = [5,4,0,3,1,6,2] 输出: 4 解释: A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2. 其中一种最长的 S[K]: S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0} 注意:
Runtime: 124 ms
Memory Usage: 19.5 MB
1 class Solution { 2 func arrayNesting(_ nums: [Int]) -> Int { 3 var nums = nums 4 var n:Int = nums.count 5 var res:Int = 0 6 for i in 0..<n 7 { 8 var cnt:Int = 1 9 while(nums[i] != i && nums[i] != nums[nums[i]]) 10 { 11 nums.swapAt(i,nums[i]) 12 cnt += 1 13 } 14 res = max(res,cnt) 15 } 16 return res 17 } 18 } 140ms 1 class Solution { 2 func arrayNesting(_ nums: [Int]) -> Int { 3 var visited: Set<Int> = [] 4 var maxLen = 0 5 for i in 0 ..< nums.count { 6 if !visited.contains(i) { 7 var next = nums[i] 8 var count = 0 9 while !visited.contains(next) { 10 visited.insert(next) 11 next = nums[next] 12 count += 1 13 } 14 maxLen = max(maxLen, count) 15 } 16 } 17 18 return maxLen 19 } 20 } 184ms 1 class Solution { 2 func arrayNesting(_ nums: [Int]) -> Int { 3 var visited = [Bool](repeating: false, count: nums.count) 4 var result = 0 5 6 for i in 0..<nums.count { 7 var j = i 8 var count = 0 9 while !visited[j] { 10 visited[j] = true 11 j = nums[j] 12 count += 1 13 } 14 result = max(result, count) 15 } 16 17 return result 18 } 19 }
|
请发表评论