leetcode 565. Array Nesting

257 篇文章 17 订阅

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 and should NOT contain duplicates.

Write a function that given an array A consisting of N integers, return the size of the largest set S[K] for this array.

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. N is an integer within the range [1, 20,000].
  2. The elements of A are all distinct.
  3. Each element of array A is an integer within the range [0, N-1].
我用的一个个枚举首索引的方法,理所应当地想着枚举每个的时候,都需要之前的数组,所以用到了cloneArray,结果TLE了。

public int arrayNesting(int[] nums) {//这个是TLE的解法
		int maxLength=-1;
		for(int firstIndex=0;firstIndex<=nums.length-1;firstIndex++){
			int[] cloneNums=nums.clone();
			int length=0;
			while(cloneNums[firstIndex]!=-1){
				length++;
				int firstTemp=cloneNums[firstIndex];
				cloneNums[firstIndex]=-1;
				firstIndex=firstTemp;
			}
			maxLength=maxLength>length?maxLength:length;
		}
		return maxLength;
}

看了大神的解法,发现不需要cloneNums,直接用原来的nums就能AC了,这个是修改后的AC的解法:

注意这道题:The array contains all integers in the range [0, N - 1],也就是说不存在一个点的入度为2。每个点的出度和入度都是1。(即不存在勺子环,只存在真正的环)。

package leetcode;

public class Array_Nesting_565 {

	public int arrayNesting(int[] nums) {//这个是修改后AC的解法
		int maxLength=-1;
		for(int firstIndex=0;firstIndex<=nums.length-1;firstIndex++){
			int length=0;
			while(nums[firstIndex]!=-1){
				length++;
				int firstTemp=nums[firstIndex];
				nums[firstIndex]=-1;
				firstIndex=firstTemp;
			}
			maxLength=maxLength>length?maxLength:length;
		}
		return maxLength;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Array_Nesting_565 a=new Array_Nesting_565();
		int[] b=new int[]{5,4,0,3,1,6,2};
		System.out.println(a.arrayNesting(b));
	}

}

我想了一下,因为最后肯定是有环,length才不会继续++的。因此无论在环中的哪个元素开始,都能顺利地跑完整个环。如题目中举例的数组,如果是从A[2]开始统计环,还是能顺利跑完整个环。如果一个数不在环内,那无论何时遍历到它都肯定不在环内。所以没必要以某某为首索引的时候重新刷新数组,因为如果它不在环里,就是不在环里。如果它在环里,那正好能统计整个环的长度,并且对于之后在环里的元素得到已遍历的结果,避免了重复遍历。


有大神用了并查集,看得我云里雾里的。(虽然大神解法后面有人评论没必要这么复杂,但是。。。看一看这个高级的思路嘛!)
public class Solution {
    class UnionFind {
        private int count = 0;
        private int[] parent, rank;
        
        public UnionFind(int n) {
            count = n;
            parent = new int[n];
            rank = new int[n];
            for (int i = 0; i < n; i++) {
                parent[i] = i;
            }
        }
        
        public int find(int p) {
            int q = parent[p];
            while (q != parent[q]) {
                q = parent[q];
            }
            parent[p] = q;
            return q;
        }
        
        public void union(int p, int q) {
            int rootP = find(p);
            int rootQ = find(q);
            if (rootP == rootQ) return;
            if (rank[rootQ] > rank[rootP]) {
                parent[rootP] = rootQ;
            }
            else {
                parent[rootQ] = rootP;
                if (rank[rootP] == rank[rootQ]) {
                    rank[rootP]++;
                }
            }
            count--;
        }
        
        public int count() {
            return count;
        }
        
        public int getMaxUnion() {
            Map<Integer, Integer> map = new HashMap<>();
            int max = 1;
            for (int i = 0; i < parent.length; i++) {
                int p = find(i);
                map.put(p, map.getOrDefault(p, 0) + 1);
                max = Math.max(max, map.get(p));
            }
            return max;
        }
    }
    
    public int arrayNesting(int[] nums) {
        int n = nums.length;
        UnionFind uf = new UnionFind(n);
        for (int i = 0; i < n; i++) {
            uf.union(i, nums[i]);
        }
        return uf.getMaxUnion();
    }
}
用题里的例子来说,一步步就是这样的。

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}

可对照https://leetcode.com/problems/array-nesting/#/solutions中的Java Solution, Union Find网页来看。

index:  0   1   2   3   4   5   6

nums:  5   4   0   3   1   6   2

parent: 0   1   2   3   4   5   6

rank:    0   0   0   0   0   0   0


union(0,5)

rootP=0;

rootQ=5;

parent[5]=0;

rank[0]++;


index:  0   1   2   3   4   5   6

nums:  5   4   0   3   1   6   2

parent: 0   1   2   3   4   0   6

rank:    1   0   0   0   0   0   0


union(1,4)

rootP=1;

rootQ=4;

parent[4]=1;

rank[1]++;


index:  0   1   2   3   4   5   6

nums:  5   4   0   3   1   6   2

parent: 0   1   2   3   1   0   6

rank:    1   1   0   0   0   0   0


union(2,0)

rootP=2;

rootQ=0;

parent[0]=2;

rank[2]++;


index:  0   1   2   3   4   5   6

nums:  5   4   0   3   1   6   2

parent: 2   1   2   3   1   0   6

rank:    1   1   1   0   0   0   0


union(3,3)

rootP=3;

rootQ=3;

return;


index:  0   1   2   3   4   5   6

nums:  5   4   0   3   1   6   2

parent: 2   1   2   3   1   0   6

rank:    1   1   1   0   0   0   0


union(4,1)

rootP=1;

rootQ=1;

return;


index:  0   1   2   3   4   5   6

nums:  5   4   0   3   1   6   2

parent: 2   1   2   3   1   0   6

rank:    1   1   1   0   0   0   0


union(5,6)

rootP=2;       ( parent[5]=2 )

rootQ=6;

parent[6]=2;

rank[2]++;


index:  0   1   2   3   4   5   6

nums:  5   4   0   3   1   6   2

parent: 2   1   2   3   1   2   2

rank:    1   1   2   0   0   0   0


union(6,2)

rootP= 2; 

rootQ=2;

return;


index:  0   1   2   3   4   5   6

nums:  5   4   0   3   1   6   2

parent: 2   1   2   3   1   2   2

rank:    1   1   2   0   0   0   0


最终有4个索引处的parent都是2。结果就是4。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值