219. Contains Duplicate II -- Python

本文介绍了一种利用字典解决数组中是否存在两个不同下标且值相同、下标差绝对值不超过k的问题的方法。通过将值作为Key,下标作为Value存入字典,可以有效地检查是否有符合条件的重复项。

219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

思路:
首先是要找到列表中可能存在的重复的值,然后重复的值之间的序号差的绝对值是否小于等于k,直接用for(不用enumerate)查找重复的值,再去查找下标,再比较,情况很多,很麻烦。这里考虑使用字典,把值作为Key,该值对应的下标作为Value,若有相同的值则Key想用直接比较Value的差值,有一个满足条件的直接返回True,否则返回False即可。

参考代码:

class Solution:
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dic = {}
        for i, v in enumerate(nums):
            if v in dic and i - dic[v] <= k:
                return True
            dic[v] = i
        return False
Facets 3 User Guide Version 3.5.0 NOTICE OF PROPRIETARY PROPERTY: THIS DOCUMENT AND THE INFORMATION CONTAINED HEREIN IS THE PROPRIETARY PROPERTY OF APPLE INC. THE POSSESSOR AGREES TO THE FOLLOWING: (I) TO MAINTAIN THIS DOCUMENT IN CONFIDENCE, (II) NOT TO REPRODUCE OR COPY IT, (III) NOT TO REVEAL OR PUBLISH IT IN WHOLE OR IN PART, (IV) ALL RIGHTS RESERVED. ACCESS TO THIS DOCUMENT AND THE INFORMATION CONTAINED HEREIN IS GOVERNED BY THE TERMS OF THE MFi LICENSE AGREEMENT. ALL OTHER USE SHALL BE AT APPLE'S SOLE DISCRETION.  DeveloperTable of Contents Introduction ....................................................................................................3 Important Information .................................................................................................3 General Requirements ....................................................................................4 Quick Start .....................................................................................................5 ATS Integration ...............................................................................................6 CaptureKit Agent Installation ......................................................................................6 Switching the ATS Version ..........................................................................................6 Viewing the ATS Trace Window ..................................................................................6 Test Plans .......................................................................................................7 Downloading the Test Plan ..........................................................................................7 Test Plan Versioning ....................................................................................................7 Required Test Cases ...................................................................................................7 Managing Product and Test Plans ...............................................................................7 Experimental Features ................................................................................................8 Exporting and Importing .......................................................................................8 Sandbox Mode ......................................................................................................8 Performing a Test Run .....................................................................................9 Test Run ......................................................................................................................9 Test Suites .................................................................................................................10 Test Case Contents ...................................................................................................10 Results .......................................................................................................................12 Failing a Test Case ...............................................................................................12 Editing Results .....................................................................................................12 Blocking a Step or Test Case ...............................................................................12 Uploading Test Results..............................................................................................13 Test Suite Features........................................................................................14 Migrate Test Suites Created in Facets 3.2 and Older ................................................14 Duplicate Test Suites .................................................................................................14 Copy a Test Suite s Test Case IDs .............................................................................14 My Suites and All Runs UI .........................................................................................15 Providing Feedback to Apple .........................................................................16 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 1 of 18Internet Connection.......................................................................................17 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 2 of 18Introduction Facets was redesigned to introduce a new workflow for running CarPlay functional tests. This new version of Facets enables: • Integration with MFi Certification Hub (MCH) to: • Retrieve Product Plan and Sample information (removing the need for the Test Plan Configuration from Facets 2) • Select, download, and update CarPlay test plans • Upload test results throughout the testing process • Control which test results are used in the certification submission to Apple • Improved test execution efficiency with more protocol validation Unlike Facets 2, Facets 3 does not use a document to record test results; this means users can run tests without needing to share a .facets file. Additionally, since the test plan is downloaded from MCH, the app no longer needs to be updated to change test plans. Important Information Facets 2 documents are not compatible with Facets 3. Both versions may need to be used until the transition to Facets 3 is complete. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 3 of 18General Requirements • Access to MFi Certification Hub (MCH) with MFi Program credentials • Product Plan with MCH records: • Configuration Record in Approved state • CarPlay Functional Tests Facets 3 record with all Sample Questionnaire fields completed • Mac running macOS Sonoma 14.2.1 or later • ATS (Accessory Test System) version 8 or later 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 4 of 18Quick Start 1. Install desired ATS (version 8 or later) 2. Install CaptureKit Agent (see CaptureKit Agent Installation below) 3. Launch Facets 3 4. Sign in with MFi credentials 5. Add Product Plan to be tested 6. Select and run test cases from the Test Plan 7. Once test run is complete, upload results to MCH 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 5 of 18ATS Integration Unlike Facets 2, Facets 3 communicates with the ATS application that is already installed on the Mac. To enable this, CaptureKit Agent must be installed (see CaptureKit Agent Installation). In Facets 3 users choose their desired capture type (e.g. Wireless CarPlay), ATS will then select the first available capture device. In most cases, the same capture can be used between multiple test cases. If users have multiple ATS installations on their computer, CaptureKit Agent needs to be installed from the desired version (see Switching ATS Version). CaptureKit Agent Installation Prior to using Facets 3, users must run the CaptureKit Agent installer in ATS by following these instructions: 1. Install the desired ATS (version 8 or later) 2. Launch ATS 3. In the ATS menu bar perform: Utilities > Install CaptureKit Agent (or similar) 4. Perform an ATS capture with accessory to ensure all dependencies are installed and up- to-date Switching the ATS Version To switch which ATS performs the Facets capture, repeat the CaptureKit Agent Installation steps from the desired ATS. Viewing the ATS Trace Window Users can choose to see the ATS trace window to appear during Facets test execution. This selection can be changed in Settings > Open ATS Window, and is enabled by default. Once enabled, the ATS trace window will open behind the Facets window and will close automatically. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 6 of 18Test Plans MFi credentials are required to add a Product Plan and download the test cases for a given Sample. Downloading the Test Plan After signing in, add a Product Plan to download its samples and corresponding Test Plan. Changes to the Configuration Record or Sample Questionnaire on MCH require updating the Product Plan in Facets. See Managing Product and Test Plans for more information. Test Plan Versioning Facets 3 has an improved Test Plan versioning system to customize which test cases are needed for a specific Product Plan. Test Plans are versioned according to the corresponding CarPlay spec version. For example, if the Product Plan is developing against Accessory Interface Specification CarPlay Addendum R5, expect the latest Test Plan version v5.x.y to be downloaded. Required Test Cases The Product Plan's Configuration Record and Sample Questionnaire on MCH determine which test cases are required (and supported) for the specific Sample under test. Unsupported test cases are not shown. Required test cases are indicated with a red asterisk (*). Additional information is shown under the info icon ( ), mainly to indicate if the test case version is incompatible with the Product Plan. Managing Product and Test Plans The Product Plan > Manage Product Plans… menu item will open the Manage Plans window. This provides the following functionality: • Retrieve latest Product Plan details from MCH with the "Update" button • Review the Release Notes of a Test Plan and copy the relevant content • Download new Test Plan versions • New Test Plans are automatically downloaded and will be denoted with a blue dot ( ) • Modify the Test Plan version for a given Product Plan. It is recommended to update to the latest spec-aligned version. This only impacts the version used locally in Facets 3. Note that this may result in submissions being rejected if the version is not suitable. • Delete downloaded items. Make sure to upload test results first. Facets automatically checks for Product Plan changes updates when signing-in after 8 hours. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 7 of 18Experimental Features The following features allow users to browse and run test cases but their results cannot be uploaded to MCH. Exporting and Importing In the Manage Plans window, Product Plan details can be exported and then imported by a different user. This allows users without a network connection to view and run test cases. Results cannot be uploaded to MCH. Sandbox Mode Sandbox Mode can be used to browse all test cases of any Test Plan version. Tests can be run but many steps will not function properly as they depend on Configuration Record and Sample Questionnaire information. Results cannot be uploaded. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 8 of 18Performing a Test Run Individual test cases or a Test Suite can be run via the toolbar, menu bar, or context menu. Test Run Initiating a test opens the "Create Test Run" window where users can configure their test run: • Test Run can be renamed • Test cases can be re-ordered When starting the run, a separate Test Run window will appear. This is where users perform test cases in the configured sequence. A Test Run can be stopped at any time and only results for completed test cases will be saved. Results are stored under "Ad-hoc Runs" in the sidebar. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 9 of 18Test Suites A Test Suite is a user-created collection of test cases. It can be created via the toolbar item or via context menu when selecting multiple test cases in the Test Plan view. Test Suites are only saved locally. Run results from a suite are located beneath the Test Suite in the "My Suites" section of the sidebar. See Test Suites Features for more information. Test Case Contents A test case contains the following components: • Test case ID, title, and description • Metrics gathered by ATS such as the wired CarPlay connection time • ATS rule errors where certain rule errors can cause the test case to fail • Sequence of steps • Blocks of repeated steps • Sample information used by steps 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 10 of 18Each step can contain the following components: ComponentDescription Step IDIdentifier used to refer to the step, appearing in the ATS trace to indicate when the step started and stopped CaptureInstructs the user to start an ATS capture Provides a choice of captures Can be configured to allow continuing the existing capture Once complete, the ATS trace is attached and can be opened InstructInstructs the user to perform a manual action VerifyPrompts the user to make an assertion on the expected test behavior Configured to fail depending on the answer Answer can be changed after the fact PromptPrompts the user to make a selection from the presented options AttachmentPrompts the user to attach one or more files MonitorUses ATS trace to perform protocol validation Receives a specific ATS event Can set variables for later use Can perform multiple programmatic assertions If Condition evaluated programmatically to enable a step 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 11 of 18Results Once a test case is complete, it will report a status of either Passed, Failed, or Blocked. Test results can be found in the Runs section, this list only shows locally saved content. Selecting a Test Run will show additional metadata, including if it was uploaded to MCH. Deleting a Test Run will remove it from the local file system; uploaded results will not be impacted. Failing a Test Case When steps fail, the test case also fails. These results should be uploaded to MCH; users select which test results to submit and failing results can be useful for tracking system health and regression testing. Editing Results For certain types of steps, like a "verify" step, the user can change their answer during test execution. This can be useful if the wrong selection was accidentally made. If a step can impact subsequent steps, it cannot be edited. A test case can also be reset to start over, during the test case or immediately after the test executed. Blocking a Step or Test Case A failure can be marked as "blocked". This can be used to communicate the inability to make a test assertion. If a step is marked as blocking the test case, the remainder of the test case is skipped. Step failures can be unblocked if the rest of the test case was not impacted. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 12 of 18Uploading Test Results When completing or stopping a test run, Facets will offer the option to "Upload Now" or "Upload Later". Users must be logged in to use the "Upload Now" option. It is recommended to upload all valid results even if they contain failures. The upload status is shown as follows: • Results have been uploaded. Click on "View Results in MCH " in the run to open results in your web browser. •Pending result upload. User must be signed in and have a network connection. •"Upload Later" was selected. To upload, click on the run and press the "Upload" button. •Result upload failed. See run for more details. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 13 of 18Test Suite Features As of Facets 3.3, all new Test Suites will be saved to only the specific testable record (Test Result or Audit) in which it was created. This is a change from earlier versions of Facets, where Test Suites were globally applied to all testable records a user had downloaded. Facets 3.3 also introduces enhancements to Test Suites, outlined below. Migrate Test Suites Created in Facets 3.2 and Older Facets 3.3 includes a utility to migrate a user s existing Test Suites to conform to the new structure in version 3.3. The utility will create a copy of each existing suite to each testable record downloaded at the time. Users then have the choice to keep or delete the copied suites. Deleting a suite will remove it from the selected testable record only. Duplicate Test Suites Users can copy a Test Suite to another testable record within the same PPID, or create additional copies of a suite in the same testable record. To do so, select the Test Suite under "My Suites" in the sidebar, Control-click to show the context menu, and select "Duplicate To…". Copy a Test Suite s Test Case IDs Users can copy all Test Case IDs in a suite to their pasteboard. To do so, select the Test Suite under "My Suites" in the sidebar, Control-click to show the context menu, and select "Copy Test Case IDs". The IDs are saved as a plain text string that can be pasted into any text editor or into the "Create Test Suite" screen. The "Create Test Suite" screen includes a field to provide copied Test Case IDs. Pasting Test Case IDs will automatically select those tests to be included in the new suite. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 14 of 18My Suites and All Runs UI Test Suites, their run results, and a results summary are collected together under "My Suites" in the sidebar. Run results are displayed beneath the suite in which the result was generated. A summary screen called "All Runs" is also displayed beneath a suite. This screen lists the results of all runs executed from the suite, plus a chart showing latest Pass/Fail/Blocked results for the suite. The chart will always reflect the latest execution. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 15 of 18Providing Feedback to Apple Report issues with Facets or its integration with ATS or Certification test cases to https:// feedbackassistant.apple.com using the “MFi Technologies” option. For app or test case issues, you may include the following: • Screenshot or screen recording displaying the issue • Saved ATS trace displaying the issue • Link to an MCH result upload that includes the issue • Log collected as soon as the issue occurred, by running the following in Terminal: sudo sysdiagnose If results are failing to upload to MCH, include the following information: • Time of upload attempt (including timezone) • MFi account username (email) • Testable record address (URL to the Test Result or Audit record in MCH) 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 16 of 18Internet Connection Facets 3 uses port 80 to communicate with the following addresses: • https://auth-assistant.apple.com • https://mficertificationhub.apple.com • https://flipper.apple.com 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 17 of 18 Apple Inc. Copyright © 2025 Apple Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior written permission of Apple Inc., with the following exceptions: Any person is hereby authorized to store documentation on a single computer or device for personal use only and to print copies of documentation for personal use provided that the documentation contains Apple’s copyright notice. No licenses, express or implied, are granted with respect to any of the technology described in this document. Apple retains all intellectual property rights associated with the technology described in this document. This document is intended to assist application developers to develop applications only for Apple-branded products. Apple Inc. One Apple Park Way Cupertino, CA 95014 408-996-1010 Apple is a trademark of Apple Inc., registered in the U.S. and other countries. APPLE MAKES NO WARRANTY OR REPRESENTATION, EITHER EXPRESS OR IMPLIED, WITH RESPECT TO THIS DOCUMENT, ITS QUALITY, ACCURACY, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. AS A RESULT, THIS DOCUMENT IS PROVIDED “AS IS,” AND YOU, THE READER, ARE ASSUMING THE ENTIRE RISK AS TO ITS QUALITY AND ACCURACY. IN NO EVENT WILL APPLE BE LIABLE FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES RESULTING FROM ANY DEFECT, ERROR OR INACCURACY IN THIS DOCUMENT, even if advised of the possibility of such damages. Some jurisdictions do not allow the exclusion of implied warranties or liability, so the above exclusion may not apply to you. 2025-06-24 | Copyright © 2025 Apple Inc. All Rights Reserved. Page 18 of 18 帮我翻译上面的文章
11-14
<think> 我们正在讨论Swiper循环模式下的DOM复制问题。用户现在询问一个具体的选择器操作是否正确: `document.querySelector('.swiper-slide-duplicate .swiper-slide-duplicate-next')` 首先,需要理解这个选择器的含义: 1. `.swiper-slide-duplicate`:这是Swiper在循环模式下复制的幻灯片(clone)的类名。 2. `.swiper-slide-duplicate-next`:这个类名看起来是自定义的,因为Swiper的标准类名中并没有这个。Swiper循环模式下复制的幻灯片会添加`swiper-slide-duplicate`类,同时根据位置会添加`swiper-slide-duplicate-prev`或`swiper-slide-duplicate-next`(注意:标准类名是`swiper-slide-duplicate-prev`和`swiper-slide-duplicate-next`,但这里用户写的是`.swiper-slide-duplicate-next`,中间没有空格,所以应该是同一个元素同时拥有这两个类?) 但是,用户的选择器是: `.swiper-slide-duplicate .swiper-slide-duplicate-next` 注意:中间有一个空格。这意味着选择的是: - 一个拥有类`swiper-slide-duplicate`的元素内部的 - 拥有类`swiper-slide-duplicate-next`的元素 这显然不是用户想要的。因为: - 在循环模式下,复制的幻灯片(即克隆的slide)本身会同时拥有`swiper-slide-duplicate`和`swiper-slide-duplicate-next`(或`swiper-slide-duplicate-prev`)这两个类,它们是在同一个元素上的。 所以,正确的选择器应该是: `.swiper-slide-duplicate.swiper-slide-duplicate-next` 注意:中间没有空格,表示同时拥有这两个类的元素。 另外,Swiper的标准类名是: - 对于复制的幻灯片,类名为:`swiper-slide swiper-slide-duplicate` - 同时,如果是复制的前一个幻灯片(即出现在最后面的那个复制品),则还会添加:`swiper-slide-duplicate-prev` - 如果是复制的后一个幻灯片(即出现在最前面的那个复制品),则还会添加:`swiper-slide-duplicate-next` 因此,用户可能想选择的是那些被复制并且作为“下一个”的幻灯片(即放在最前面的复制品)。那么正确的选择器是: `.swiper-slide-duplicate.swiper-slide-duplicate-next` 但是,我们通常不需要直接操作这些复制品,因为Swiper提供了API来获取当前真实的索引(`realIndex`)以及事件处理方式。直接操作DOM复制节点可能会遇到问题,因为它们是克隆的,可能不包含Vue添加的事件监听器和状态。 所以,建议用户使用Swiper提供的事件和API来操作,而不是直接操作DOM。 回答结构: 1. 指出选择器错误:中间的空格导致选择的是子元素,而正确的应该是同一个元素同时拥有两个类(无空格)。 2. 解释Swiper循环模式下的类名机制。 3. 给出正确的选择器写法(如果需要操作这些复制节点)。 4. 提醒:直接操作复制节点可能存在风险(如事件监听丢失),建议使用Swiper API。 同时,根据用户之前的问题,他们遇到的问题是循环模式下复制节点的事件监听问题,所以再次强调使用Swiper事件代理的重要性。 最后,生成相关问题。 </think>### 关于 `document.querySelector('.swiper-slide-duplicate .swiper-slide-duplicate-next')` 操作的分析 #### 该操作存在的问题 1. **选择器语法错误**: ```javascript // 错误的层级关系(中间有空格) document.querySelector('.swiper-slide-duplicate .swiper-slide-duplicate-next'); // 正确的写法(使用并列类选择器) document.querySelector('.swiper-slide-duplicate.swiper-slide-duplicate-next'); ``` - 空格表示层级关系(父元素 .swiper-slide-duplicate 内的子元素 .swiper-slide-duplicate-next) - 实际需要的应该是**同时拥有这两个类**的元素(并列类选择器) 2. **类名准确性**: - Swiper 循环模式生成的复制元素类名是 `swiper-slide-duplicate` - 方向标识是 `swiper-slide-duplicate-prev` 和 `swiper-slide-duplicate-next` - 建议直接使用官方类名避免自定义错误 3. **更可靠的获取方式**: ```javascript // 通过 Swiper API 获取 const duplicateSlides = swiper.slides.filter(slide => slide.classList.contains('swiper-slide-duplicate') ); // 获取特定位置的复制元素 const duplicateNext = duplicateSlides.find(slide => slide.classList.contains('swiper-slide-duplicate-next') ); ``` #### 推荐解决方案 1. **使用 Swiper 原生 API**: ```javascript // 初始化时保存实例 const swiper = new Swiper('.swiper', { loop: true, on: { init: function() { // 获取所有复制元素 const duplicates = this.slides.filter( slide => slide.classList.contains('swiper-slide-duplicate') ); // 获取特定复制元素 const duplicateNext = duplicates.find( slide => slide.classList.contains('swiper-slide-duplicate-next') ); } } }); ``` 2. **事件代理替代 DOM 操作**: ```javascript swiper.on('click', (swiper, event) => { const clickedSlide = event.target.closest('.swiper-slide'); if (clickedSlide.classList.contains('swiper-slide-duplicate')) { const slideType = clickedSlide.classList.contains('swiper-slide-duplicate-next') ? 'next' : 'prev'; console.log(`点击了${slideType}方向的复制slide`); } }); ``` 3. **动态内容处理方案**: ```vue <swiper :key="refreshKey" @after-init="handleSwiperInit"> <swiper-slide v-for="item in items" :class="{ 'custom-duplicate-next': isDuplicateNext(item.id) }"> <!-- 内容 --> </swiper-slide> </swiper> ``` ```javascript methods: { handleSwiperInit(swiper) { this.swiperInstance = swiper; }, isDuplicateNext(id) { return this.swiperInstance?.slides.some(slide => slide.dataset.id === id && slide.classList.contains('swiper-slide-duplicate-next') ); } } ``` #### 注意事项 1. **循环模式下的索引偏移**: - 复制元素会导致 `slideIndex` 与实际索引不一致 - 始终使用 `swiper.realIndex` 获取真实索引 ```javascript swiper.on('slideChange', () => { console.log('真实索引:', swiper.realIndex); }); ``` 2. **避免直接操作复制元素**: - 复制元素是临时创建的镜像节点 - 任何直接修改会在 Swiper 更新时丢失 - 应通过数据驱动方式更新内容 3. **性能优化**: ```javascript new Swiper('.swiper', { loop: true, loopAdditionalSlides: 2, // 仅复制必要数量 loopPreventsSlide: true // 防止边界滑动异常 }); ``` > 最佳实践是通过 Swiper 的 API 和事件系统操作元素,避免直接查询 DOM 类名。如需精确控制,应结合 `data-*` 属性和 Swiper 的索引系统[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值