leetcode 457. Circular Array Loop 双指针 + 循环判断
来源:互联网 发布:达内java速成班 编辑:程序博客网 时间:2024/06/05 23:55
You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it’s negative (-n), move backward n steps. Assume the first element of the array is forward next to the last element, and the last element is backward next to the first element. Determine if there is a loop in this array. A loop starts and ends at a particular index with more than 1 element along the loop. The loop must be “forward” or “backward’.
Example 1: Given the array [2, -1, 1, 2, 2], there is a loop, from index 0 -> 2 -> 3 -> 0.
Example 2: Given the array [-1, 2], there is no loop.
Note: The given array is guaranteed to contain no element “0”.
Can you do it in O(n) time complexity and O(1) space complexity?
题意很简单,就是一个循环的判断,这道题可以使用双指针来判断,要注意的是双指针的移动要注意保持方向一致
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <cmath>using namespace std;class Solution {public: bool circularArrayLoop(vector<int>& nums) { for (int i = 0; i < nums.size(); i++) { if (nums[i] == 0) continue; int j = i, k = getNextIndex(i, nums); while (nums[i] * nums[k] > 0 && nums[i] * nums[getNextIndex(k,nums)] > 0) { if (j == k) { if (j == getNextIndex(j, nums)) break; else return true; } else { j = getNextIndex(j, nums); k = getNextIndex(getNextIndex(k, nums), nums); } } } return false; } int getNextIndex(int i, vector<int>& nums) { int size = nums.size(); if (i + nums[i] > 0) return (i + nums[i]) % size; else return ((i + nums[i]) % size + size); }};
- leetcode 457. Circular Array Loop 双指针 + 循环判断
- LeetCode 457. Circular Array Loop
- Leetcode 457. Circular Array Loop
- {LeetCode} 457. Circular Array Loop
- 457. Circular Array Loop
- Circular Array
- avalon循环分支判断ms-if-loop
- Circular microphone array 1
- Circular Array implement Queue
- 循环单链表(circular list)
- 循环队列(circular queue)
- 循环队列(Circular Queue)
- 队列(queue)的链表(list)实现及循环数组(circular array)实现 C++实现
- 【数据结构与算法基础】以数组实现的循环队列 / Circular Queue implemented by array
- 队列(queue)的链表(list)实现及循环数组(circular array)实现 C++实现
- 判断 circular rotation
- leetcode Remove Duplicates from Sorted Array 双指针
- leetcode 88. Merge Sorted Array-合并链表|双指针
- 判断网络状态
- POJ3261 Milk Patterns 【后缀数组】
- 14-CSS3提高 重点部分 盒模型 浮动和定位
- MOOC清华《VC++面向对象与可视化程序设计》第4章:鼠标实例程序(光标九宫格)
- 详解DNS域名解析全过程
- leetcode 457. Circular Array Loop 双指针 + 循环判断
- android 代码怎么实时监控连接当前wifi热点的设备的连接或断开事件?
- kernel启动流程第二阶段
- css居中思路整理
- JAVA的数组
- zabbix 从部署到快速上手
- Python3.6爬虫练习之爬取全国大学省份数据
- Qt状态机场景模拟-续
- HTML 依赖注入 内置服务