A common method for finding duplicate data in Solidity arrays is to use a hash map (typically implemented via mapping). This approach enables us to detect duplicate elements with high efficiency (with an average time complexity close to O(n)). I will demonstrate a simple example where we use a mapping to track the occurrence count of each element in the array to identify duplicates.
solidity// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract DuplicateFinder { // Function to find duplicate elements in an array function findDuplicates(uint[] memory arr) public pure returns (uint[] memory) { // Used to track the occurrence count of each element mapping(uint => uint) count; // Dynamic array to store the results uint[] memory duplicates; // Iterate through the input array, updating the count in the mapping for (uint i = 0; i < arr.length; i++) { count[arr[i]]++; // If the count reaches 2, it indicates a duplicate if (count[arr[i]] == 2) { // Add the duplicate element to the results array duplicates.push(arr[i]); } } return duplicates; } }
Analysis:
- Initialization: We use
mapping(uint => uint)to track the occurrence count of each element in the array. Additionally, we create a dynamic arrayduplicatesto store the identified duplicate elements. - Traversing the array: We iterate through the input array, incrementing the count in the
mappingfor each encountered element. - Detecting duplicates: After updating the count, we check if it reaches 2; if so, it indicates that the element has appeared before, thus being a duplicate. We then add it to the
duplicatesarray. - Returning results: The function finally returns the array containing all identified duplicate elements.
Notes:
- In actual contracts, additional considerations are needed, such as the function's visibility (whether it should be
publicorexternal), whether it should be exposed externally, and call permissions. - Furthermore, this method only records the first occurrence of duplicates; if an element appears multiple times (more than twice) in the array, the above implementation will not add it again to the result array. This can be adjusted based on specific requirements.
This is one method for finding duplicate data in Solidity arrays along with its implementation. In practical applications, this method is typically efficient and easy to implement.
2024年6月29日 12:07 回复