-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path565-ArrayNesting.go
More file actions
59 lines (51 loc) · 1.85 KB
/
565-ArrayNesting.go
File metadata and controls
59 lines (51 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
// 565. Array Nesting
// You are given an integer array nums of length n where nums is a permutation of the numbers in the range [0, n - 1].
// You should build a set s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... } subjected to the following rule:
// The first element in s[k] starts with the selection of the element nums[k] of index = k.
// The next element in s[k] should be nums[nums[k]], and then nums[nums[nums[k]]], and so on.
// We stop adding right before a duplicate element occurs in s[k].
// Return the longest length of a set s[k].
// Example 1:
// Input: nums = [5,4,0,3,1,6,2]
// Output: 4
// Explanation:
// nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
// One of the longest sets s[k]:
// s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
// Example 2:
// Input: nums = [0,1,2]
// Output: 1
// Constraints:
// 1 <= nums.length <= 10^5
// 0 <= nums[i] < nums.length
// All the values of nums are unique.
import "fmt"
func arrayNesting(nums []int) int {
res, visited := 0, make([]bool, len(nums))
max := func (x, y int) int { if x > y { return x; }; return y; }
for i := range nums {
cur, count := i, 0
for !visited[cur] {
count++
visited[cur] = true
cur = nums[cur]
}
res = max(res, count)
}
return res
}
func main() {
// Example 1:
// Input: nums = [5,4,0,3,1,6,2]
// Output: 4
// Explanation:
// nums[0] = 5, nums[1] = 4, nums[2] = 0, nums[3] = 3, nums[4] = 1, nums[5] = 6, nums[6] = 2.
// One of the longest sets s[k]:
// s[0] = {nums[0], nums[5], nums[6], nums[2]} = {5, 6, 2, 0}
fmt.Println(arrayNesting([]int{5,4,0,3,1,6,2})) // 4
// Example 2:
// Input: nums = [0,1,2]
// Output: 1
fmt.Println(arrayNesting([]int{0,1,2})) // 1
}