457. Circular Array Loop

本文介绍了一种在循环数组中检测是否存在长度大于1的环的方法。利用快慢指针技术,通过修改已遍历过的元素值来避免重复访问,实现了O(n)的时间复杂度和O(1)的空间复杂度。
问题描述

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?
题目链接:


思路分析

给一个数组,里面元素非零。如果元素是正数就前进n步,反之如果是负数就后退n步。数组是首尾相连循环的。loop中元素个数要大于1,判断数组中是否存在loop。

类似于链表的环的问题,只不过是存放在数组中了而已。创建一个计算下一个位置的函数getIndex,判断有无向左过0的情况,计算得到不同的index。

然后开始从第一个数字开始循环,我们会将判定为不同的path的元素都设为0,所以要先判断一下。然后用两个快慢指针,从i处开始循环,(注意要判断快指针的两次跳跃都是合法的)只要循环的方向不变,也就是nums的值符号是相同的,就继续循环。总会有slow和fast碰上的时候,这时要判断是否是只有一个元素的循环,是的话breakk,如果不是就可以返回true了。

对于快慢指针循环之后,要将之前这条不同的循环上的节点都置0,循环条件同样是nums的值要同符号,防止再次进入这条路径。这也是我们for循环中要判0的原因。

代码
class Solution {
public:
    bool circularArrayLoop(vector<int>& nums) {
        for (int i = 0; i < nums.size(); i++){
            if (nums[i] == 0)
                continue;
            int slow = i;
            int fast = getIndex(slow, nums);
            while (nums[i] * nums[fast] > 0 && nums[i] * nums[getIndex(fast, nums)] > 0){
                if (slow == fast){
                    if (slow == getIndex(slow, nums))
                        break;
                    return true;
                }
                slow = getIndex(slow, nums);
                fast = getIndex(getIndex(fast, nums), nums);
            }
            slow = i;
            int val = nums[slow];
            while(nums[slow] * val > 0){
                int next = getIndex(slow, nums);
                nums[slow] = 0;
                slow = next;
            }
        }
        return false;
    }

    int getIndex(int i, vector<int>& nums){
        int n = nums.size();
        return i + nums[i] >= 0? (i + nums[i]) % n : n + ((i + nums[i]) % n);
    }
};

时间复杂度: O(n)
空间复杂度: O(1


反思

java和c++的模除不同于python的模除,python中模除的结果永远是非负的,而c++则是可以为负数的,这也是我们计算index的基础。

把刚刚封装的组件重新封装成这样使用方式的组件<template> <uni-popup ref="popup" type="center" :mask-click="false" @change="onPopupChange"> <view class="preview-container" :style="{ backgroundColor: options.background }"> <swiper class="preview-swiper" :current="currentIndex" :circular="options.loop" @change="onSwiperChange" @touchmove.stop @touchend.stop > <swiper-item v-for="(url, index) in options.urls" :key="index"> <view class="preview-item" v-if="index === currentIndex" @touchstart="onTouchStart(index)" @touchmove="onTouchMove(index)" @touchend="onTouchEnd(index)" @tap="onTap(index)" > <image class="zoom-image" :src="url" mode="aspectFit" :style="{ transform: `scale(${scaleValues[index]}) translate(${translateX[index]}px, ${translateY[index]}px)`, transition: isScaling ? 'none' : 'transform 0.1s ease-out' }" @load="onImageLoad(index)" @error="onImageError(index)" /> </view> </swiper-item> </swiper> </view> </uni-popup> </template> <script> export default { name: 'ZyPreviewImage', data() { return { options: { current: 0, urls: [], indicator: true, loop: true, background: 'rgba(0, 0, 0, 0.9)' }, currentIndex: 0, scaleValues: [], translateX: [], translateY: [], touch: { startX: 0, startY: 0, startScale: 1, lastTapTime: 0, startTranslateX: 0, startTranslateY: 0 }, isScaling: false, scaleMin: 0.5, scaleMax: 4 } }, methods: { show(options = {}) { this.options = { current: options.current || 0, urls: options.urls || [], indicator: options.indicator !== undefined ? options.indicator : true, loop: options.loop !== undefined ? options.loop : true, background: options.background || 'rgba(0, 0, 0, 0.9)' } this.currentIndex = this.options.current this.scaleValues = new Array(this.options.urls.length).fill(1) this.translateX = new Array(this.options.urls.length).fill(0) this.translateY = new Array(this.options.urls.length).fill(0) this.$refs.popup.open() }, hide() { this.$refs.popup.close() }, onPopupChange(e) { if (e.show) { uni.pageScrollTo({ scrollTop: 0, duration: 0 }) } }, onSwiperChange(e) { this.currentIndex = e.detail.current }, onImageLoad(index) { // 图片加载完成 }, onImageError(index) { // 图片加载失败 }, onTap(index) { const now = Date.now() if (now - this.touch.lastTapTime < 300) { // 双击放大 this.scaleValues[index] = this.scaleValues[index] > 1.5 ? 1 : 2 } else { // 单击关闭 this.hide() } this.touch.lastTapTime = now }, onTouchStart(index) { this.touch.startX = event.touches[0].clientX this.touch.startY = event.touches[0].clientY this.touch.startScale = this.scaleValues[index] this.touch.startTranslateX = this.translateX[index] this.touch.startTranslateY = this.translateY[index] this.isScaling = true }, onTouchMove(index) { const dx = event.touches[0].clientX - this.touch.startX const dy = event.touches[0].clientY - this.touch.startY // 缩放逻辑 const distance = Math.sqrt(dx * dx + dy * dy) const scaleDelta = distance / 100 const newScale = Math.min(Math.max(this.touch.startScale + scaleDelta, this.scaleMin), this.scaleMax) this.scaleValues[index] = newScale // 拖动逻辑 this.translateX[index] = this.touch.startTranslateX + dx this.translateY[index] = this.touch.startTranslateY + dy }, onTouchEnd(index) { // 缩放边界判断 if (this.scaleValues[index] < 1) { this.scaleValues[index] = 1 } // 拖动边界判断 const maxX = (this.scaleValues[index] - 1) * window.innerWidth this.translateX[index] = Math.min(Math.max(this.translateX[index], -maxX), maxX) this.translateY[index] = Math.min(Math.max(this.translateY[index], -maxX), maxX) this.isScaling = false } } } </script> <style lang="scss"> .preview-container { position: relative; width: 100vw; height: 100vh; overflow: hidden; display: flex; justify-content: center; align-items: center; } .preview-swiper { width: 100%; height: 100%; } .preview-item { width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; overflow: hidden; } .zoom-image { width: 100%; height: 100%; transform-origin: center center; image-rendering: crisp-edges; -ms-interpolation-mode: nearest-neighbor; } </style>
最新发布
09-06
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值