Twitter online 两题 | 勇幸|Thinking
今天有个群里发了两道twitter online的题目,看了下,练手写一下。
题一:
A zero-indexed array A consisting of N different integers is given. The array contains all integers in the range [0..N−1]. Sets S[K] for 0 ≤ K < N are defined as follows: S[K] = { A[K], A[A[K]], A[A[A[K]]], ... }. Sets S[K] are finite for each K.
Write a function:
class Solution { public int solution(int[] A); }
that, given an array A consisting of N integers, returns the size of the largest set S[K] for this array. The function should return 0 if the array is empty.
原题不存在数组元素不小于len的情况,后面的两种解法都是考虑元素有大于len的情况,开始没看清,做了个稍微复杂的情况;区别在于,如果元素不越界,S集合就是一个个的环,当元素值等于下标值,环大小为1;如果元素有越界情况,则S集合就不一定是环,就需要记录之前遍历的集合大小了,先给出本题的解法,后面讨论元素越界的情况。
Read full article from Twitter online 两题 | 勇幸|Thinking
No comments:
Post a Comment