697 Degree of an Array

本文介绍了一种算法,用于寻找给定数组中具有相同度的最短连续子数组。通过使用两个HashMap来记录元素频率及它们的起始和结束位置,从而实现了高效查找。

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

697 Degree of an Array JAVA实现

  • 题目描述:Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum frequency of any one of its elements.

    Your task is to find the smallest possible length of a (contiguous) subarray of nums, that has the same degree as nums.

    • Example 1:
    Input: [1, 2, 2, 3, 1]
    Output: 2
    Explanation: 
    The input array has a degree of 2 because both elements 1 and 2 appear twice.
    Of the subarrays that have the same degree:
    [1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
    The shortest length is 2. So return 2.
    • Example 2:
    Input: [1,2,2,3,1,4,2]
    Output: 6
  • 题目大意:给定一个非空数组,数组中的“度”表示数组中的元素出现最多次数的一个元素的次数,目的是在nums数组中去寻找小的子数组(必须连续),使子数组的度与原数组相同。

  • 思路:使用hashmap,建立两个hasmap,一个存储各个元素出现的次数,以寻找最大度,另一个存储,数组中每个元素出现的初始位置与结束位置,找到最大的度之后,再次遍历数组

  • 代码

    package Array;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class Solution {
      public int findShortestSubArray(int[] nums) {
          int degree = 0;
          int minSize = nums.length;
          Map<Integer, Integer> map = new HashMap<>();
          Map<Integer, Integer[]> map2 = new HashMap<>();
          for(int i=0;i<nums.length;i++) {
              map.put(nums[i], map.getOrDefault(nums[i],0) + 1);
              degree = Math.max(degree, map.get(nums[i]));
              if (map2.get(nums[i]) == null) {
                  map2.put(nums[i], new Integer[2]);
              }
              Integer[] numsRange = map2.get(nums[i]);
              if(numsRange[0]==null) numsRange[0] = i;
              numsRange[1] = i;
          }
          for (Integer key : map.keySet()) {
              if (map.get(key) != degree) {
                  continue;
              }
              Integer[] rang = map2.get(key);
              minSize = Math.min(minSize, rang[1] - rang[0] + 1);
          }
    
          return minSize;
    
      }
    
    
    }
    
### Vision GNN 实现概述 对于Vision GNN中的图像值图节点,这类模型旨在将图形神经网络应用于计算机视觉领域。具体来说,在这些架构中,图像被建模成图结构,其中像素或区域作为节点,并通过边连接起来形成复杂的拓扑关系[^1]。 一种常见的做法是在构建这样的图时,利用预训练的CNN提取局部特征来初始化节点表示。之后应用消息传递机制更新节点状态直到收敛于稳定的表达形式。这种设计允许捕捉空间依赖性和上下文信息,从而增强对复杂模式的理解能力[^2]。 下面给出了一种基于PyTorch Geometric库实现简单版本Vision-GNN的方法: ```python import torch from torch_geometric.nn import MessagePassing, global_mean_pool from torch_geometric.utils import add_self_loops, degree class SimpleVisionGNN(MessagePassing): def __init__(self, input_dim, hidden_dim, output_dim): super(SimpleVisionGNN, self).__init__(aggr='mean') # 定义层间转换函数 self.lin = torch.nn.Linear(input_dim, hidden_dim) self.out_lin = torch.nn.Linear(hidden_dim, output_dim) def forward(self, x, edge_index): # 添加自环并计算度数矩阵 edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0)) deg = degree(edge_index[0], x.size(0), dtype=x.dtype).pow(-0.5) norm = deg[edge_index[0]] * deg[edge_index[1]] # 应用线性变换和激活函数 x = self.lin(x).relu() # 执行消息传播 return self.propagate(edge_index, size=(x.size(0), x.size(0)), x=x, norm=norm) def message(self, x_j, norm): # 计算标准化后的消息 return norm.view(-1, 1) * x_j def update(self, aggr_out): # 更新节点嵌入 return self.out_lin(aggr_out) # 使用示例 if __name__ == "__main__": from torchvision.models import resnet18 from PIL import Image import numpy as np from skimage.segmentation import slic from sklearn.preprocessing import normalize img_path = "path_to_image.jpg" # 加载图片并分割为超像素 image = np.array(Image.open(img_path)) segments = slic(image=image, n_segments=100, compactness=10) # 提取每个超像素的颜色均值作为初始特征向量 features = [] for i in range(segments.max() + 1): mask = (segments == i) color_avg = image[mask].mean(axis=0)[:3] features.append(color_avg / 255.) feature_matrix = torch.tensor(normalize(features)).float() # 构造邻接表(这里简化处理) edges = [[i, j] for i in range(len(features)) for j in range(i+1, len(features))] edge_index = torch.LongTensor(edges).t().contiguous() model = SimpleVisionGNN(input_dim=feature_matrix.shape[-1], hidden_dim=64, output_dim=16) with torch.no_grad(): out = model(feature_matrix, edge_index) print(out) ``` 此代码片段展示了如何创建一个简单的Vision GNN类`SimpleVisionGNN`以及其基本工作流程。为了更深入理解该主题,建议查阅更多资源了解最新进展和技术细节。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值