Array Nesting (第十四周 数组)

本文介绍了一种名为ArrayNesting的算法,该算法通过深度优先搜索寻找数组中最大不重复子集的大小。通过对数组进行遍历并利用标记避免重复访问,有效地解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Array Nesting (第十四周 数组)

A zero-indexed array A consisting of N different integers is given. The array contains all integers in the range [0, N - 1].

Sets S[K] for 0 <= K < N are defined as follows:

S[K] = { A[K], A[A[K]], A[A[A[K]]], … }.

Sets S[K] are finite for each K and should NOT contain duplicates.

Write a function that given an array A consisting of N integers, return the size of the largest set S[K] for this array.

算法思路

(1)题目其实非常简单,其实就是用深度优先搜索就可以了。比如先设置index=A[i], 然后设置index=A[index],直到index再次等于A[i]
(2)但其实一开始我并没有,而是发现超时了。然后我就再看了一下例题,发现了一个规律。

S[0]={A[0]=5, A[5]=6, A[6]=2, A[2]=0};
S[2]={A[2]=0,A[0]=5, A[5]=6, A[6]=2};
S[5]={A[5]=6, A[6]=2,A[2]=0,A[0]=5};
S[6]={A[6]=2, A[2]=0,A[0]=5, A[5]=6};

其中S[0],S[2],S[5]与S[6]包含的元素相同。也就是说,并不用每一个元素都变量,也就是并不用对数组中的每一个元素都执行dfs,当一个元素在之前的dfs被访问过,以后也就不用再访问了。也就是把原来代码中的一句注释掉即可。

算法代码

class Solution {
private:
    bool flag[30000];
    int res;
public:
    int arrayNesting(vector<int>& nums) {
        int n = nums.size();
        for(int i = 0 ; i < n; i++)
            flag[i] = false;
        res = 0;
        for (int i = 0; i < n; ++i)
        {
            dfs(nums,i,n,0);
        }
        return res;
    }
    void dfs(vector<int>& nums, int index, int n, int d){
        if(index >= 0 && index < n && !flag[index]){
            flag[index] = true;
            dfs(nums,nums[index],n,d + 1);
            //flag[index] = false;
        }
        else{
            if(res < d){
                res = d;
            }
        }
    }
};
import pickle import numpy as np import matplotlib.pyplot as plt from PIL import Image import sys def load_pkl_data(/Users/yangguang/Documents/python_workspace/data/2025-07-15T14:55:55.540272.pkl): """安全加载PKL文件数据""" try: with open(/Users/yangguang/Documents/python_workspace/data/2025-07-15T14:55:55.540272.pkl, 'rb') as f: # 尝试不同编码方式解决兼容性问题 try: return pickle.load(f) except UnicodeDecodeError: return pickle.load(f, encoding='latin1') except Exception as e: print(f"加载PKL文件失败: {str(e)}") sys.exit(1) def diagnose_data_structure(data): """诊断数据结构并返回报告""" report = { 'data_type': type(data).__name__, 'keys': [], 'nested_levels': 0, 'contains_image': False } if isinstance(data, dict): report['keys'] = list(data.keys()) # 检查嵌套层级 def count_nesting(obj, level=1): if isinstance(obj, dict): return max([count_nesting(v, level+1) for v in obj.values()] + [level]) elif isinstance(obj, (list, tuple)): return max([count_nesting(item, level+1) for item in obj] + [level]) if obj else level return level report['nested_levels'] = count_nesting(data) # 检查是否包含图像数据 for value in data.values(): if isinstance(value, np.ndarray) and value.ndim in (2, 3): report['contains_image'] = True break return report def find_image_data(data, depth=0, max_depth=5): """在数据结构中递归查找图像数据""" # 防止无限递归 if depth > max_depth: return None # 如果是NumPy数组且符合图像维度 if isinstance(data, np.ndarray): if data.ndim == 2: # 灰度图像 (高度, 宽度) return data elif data.ndim == 3: # 彩色图像 (高度, 宽度, 通道) return data # 如果是字典,检查常见键名 if isinstance(data, dict): # 常见图像键名列表 image_keys = ['image', 'img', 'data', 'pixels', 'array', 'frame', 'picture'] # 优先检查常见键名 for key in image_keys: if key in data: result = find_image_data(data[key], depth+1, max_depth) if result is not None: return result # 深度搜索所有值 for value in data.values(): result = find_image_data(value, depth+1, max_depth) if result is not None: return result # 如果是列表或元组 elif isinstance(data, (list, tuple)): for item in data: result = find_image_data(item, depth+1, max_depth) if result is not None: return result return None def analyze_image(image_data): """分析图像数据并返回信息""" if not isinstance(image_data, np.ndarray): try: # 尝试转换为NumPy数组 image_data = np.array(image_data) except Exception as e: return {"error": f"无法转换为图像数组: {str(e)}"} info = { 'dimensions': image_data.ndim, 'shape': image_data.shape, 'dtype': str(image_data.dtype), 'resolution': None, 'channels': None } # 获取分辨率 if image_data.ndim == 2: # 灰度图像 (高度, 宽度) height, width = image_data.shape info['resolution'] = f"{width}×{height}" info['channels'] = 1 elif image_data.ndim == 3: # 彩色图像 (高度, 宽度, 通道) height, width, channels = image_data.shape info['resolution'] = f"{width}×{height}" info['channels'] = channels return info def display_images(image_data, num_images=6, title="提取的图像数据"): """显示图像数据""" if not isinstance(image_data, np.ndarray): print("无法显示: 图像数据不是NumPy数组") return # 处理单个图像 if image_data.ndim == 2 or (image_data.ndim == 3 and image_data.shape[2] in [1, 3, 4]): plt.figure(figsize=(6, 6)) plt.imshow(image_data, cmap='gray' if image_data.ndim == 2 or image_data.shape[2] == 1 else None) plt.title(title) plt.axis('off') plt.show() return # 处理多个图像 if image_data.ndim == 4: # 图像集合 (数量, 高度, 宽度, 通道) num_images = min(num_images, image_data.shape[0]) fig, axes = plt.subplots(1, num_images, figsize=(12, 3)) for i in range(num_images): ax = axes[i] if num_images > 1 else axes img = image_data[i] if img.shape[2] == 1: # 单通道灰度图 ax.imshow(img[:, :, 0], cmap='gray') else: # 多通道彩色图 ax.imshow(img) ax.axis('off') plt.suptitle(f"{title} (前{num_images}张)") plt.tight_layout() plt.show() def main(pkl_file): """主处理函数""" print(f"加载文件: {pkl_file}") data = load_pkl_data(pkl_file) # 诊断数据结构 print("\n=== 数据结构诊断 ===") report = diagnose_data_structure(data) print(f"数据类型: {report['data_type']}") print(f"包含的键: {report['keys'][:10]}{'...' if len(report['keys']) > 10 else ''}") print(f"嵌套层级: {report['nested_levels']}") print(f"包含图像数据: {'是' if report['contains_image'] else '否'}") # 查找图像数据 print("\n=== 搜索图像数据 ===") image_data = find_image_data(data) if image_data is None: print("错误: 未找到图像数据") return # 分析图像 print("\n=== 图像分析 ===") image_info = analyze_image(image_data) print(f"图像维度: {image_info['dimensions']}") print(f"图像形状: {image_info['shape']}") if image_info['resolution']: print(f"分辨率: {image_info['resolution']}") print(f"通道数: {image_info['channels']}") else: print("警告: 无法确定分辨率") # 显示图像 print("\n=== 显示图像 ===") display_images(image_data) if __name__ == "__main__": # 替换为您的PKL文件路径 PKL_FILE = "image_data.pkl" main(PKL_FILE) 在Mac上运行该代码 有问题 帮我改改
最新发布
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值