565. Array Nesting

约定不等于承诺〃 2022-01-25 23:11 246阅读 0赞
  1. 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.
  2. 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.
  3. Example 1:
  4. Input: A = [5,4,0,3,1,6,2]
  5. Output: 4
  6. Explanation:
  7. A[0] = 5, A[1] = 4, A[2] = 0, A[3] = 3, A[4] = 1, A[5] = 6, A[6] = 2.
  8. One of the longest S[K]:
  9. S[0] = {A[0], A[5], A[6], A[2]} = {5, 6, 2, 0}
  10. Note:
  11. N is an integer within the range [1, 20,000].
  12. The elements of A are all distinct.
  13. Each element of A is an integer within the range [0, N-1].

读完题目,首先得明白一个点,无论如何,题目必定存在一个循环,然后我们为了防止重复寻找,使用“做标记”的方法标记找过的节点。

  1. public int arrayNesting(int[] nums) {
  2. int ans = 0;
  3. for(int i = 0; i < nums.length; ++i) {
  4. if(nums[i] != -1) {
  5. int start = nums[i], count = 0;
  6. while(nums[start] != -1) {
  7. int temp = start;
  8. start = nums[start];
  9. ++count;
  10. nums[temp] = -1;
  11. }
  12. ans = Math.max(ans, count);
  13. }
  14. }
  15. return ans;
  16. }

发表评论

表情:
评论列表 (有 0 条评论,246人围观)

还没有评论,来说两句吧...

相关阅读

    相关 bmp转rgb565在framebuffer中显示

    需求:在kernel中自定义显示图片 解决办法:在网上找了很多方法,都是去替换的,那样就有了很大的局限性,还比较麻烦,所以经过研究最后找到此方法: 首先:得到一副图片e