题目
算法思路
思路一(暂时无解)
思路分析
由题,想创建一个数组存放S,然后通过下个元素值和S数组里面进行比较是否有相同的,如果有相同的则返回ans(长度),但是一直有问题,没有想出思路。
源码
class Solution {
public int arrayNesting(int[] nums) {
int ans=0;
int temp=nums[0];
int[] s=new int[nums.length+1];
s[0]=temp;
for(int i=0;i<s.length;i++){
if(nums[temp]!=s[i]){
s[i+1]=nums[temp];
ans++;
}
}
return ans;
}
}
时间和空间复杂度
思路二(图)
思路分析
执行题目操作会执行一个循环,只需要记录每个环执行后的长度,然后找出长度最大的那个长度返回即可。
源码
class Solution {
public int arrayNesting(int[] nums) {
int ans = 0
int n = nums.length;
for (int i = 0; i < n; i++) {
int cnt = 0;
//while所有结束就是一个环(nums[i] > n)
while (nums[i] < n) {
int num = nums[i];//记录当前索引的值,方便传给i
nums[i] = n; //把一个环内的过程中经历过的变为7,这样nums[i]<n就不会重复进入扫描过的元素
i = num;//i记录指向下一个的元素的位置索引
cnt++;
}
ans = Math.max(ans, cnt);
}
return ans;
}
}
时间和空间复杂度
时间复杂度:O(n)
空间复杂度:O(1)
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/array-nesting/solution/shu-zu-qian-tao-by-leetcode-solution-7ur3/
来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处
所用API
总结(深度优先搜索)
深度优先搜索属于图算法的一种,沿着树的深度遍历树的节点,尽可能深的搜索树的分支。
基本思路
- 访问顶点v
- 依次从v的未被访问的邻接点出发,对图进行深度优先遍历;直至图中和v有路径相通的顶点都被访问
- 若此时图中尚有顶点未被访问,则从一个未被访问的顶点出发,重新进行深度优先遍历,直到图中所有顶点均被访问过为止。
1.DFS模板(递归)
/*
* Return true if there is a path from cur to target.
*/
boolean DFS(Node cur, Node target, Set<Node> visited) {
return true if cur is target;
for (next : each neighbor of cur) {
if (next is not in visited) {
add next to visted;
return true if DFS(next, target, visited) == true;
}
}
return false;
}
2.DFS模板(显式栈)
链接
递归解决方案的优点是它更容易实现。 但是,存在一个很大的缺点:如果递归的深度太高,你将遭受堆栈溢出。
/*
* Return true if there is a path from cur to target.
*/
boolean DFS(int root, int target) {
Set<Node> visited;
Stack<Node> s;
add root to s;
while (s is not empty) {
Node cur = the top element in s;
return true if cur is target;
for (Node next : the neighbors of cur) {
if (next is not in visited) {
add next to s;
add next to visited;
}
}
remove cur from s;
}
return false;
}