398. Random Pick Index

本文介绍了一种使用Java实现的LeetCode题目解决方案,通过构造一个类来存储数组并随机返回目标值的位置。该方法首先将输入数组复制到类内部,然后通过遍历数组找到所有目标值出现的位置,并从中随机选取一个返回。

  不定期更新leetcode解题java答案。

  采用pick one的方式选择题目。

  题意为构造一个新类,拥有两个功能,其一为构造函数,用于存储数组(可能有重复值),另一个为寻找目标值的数组位置。要求寻找的目标若干位置拥有等可能的随机返回。

  同简单的搜寻数组类似,只是加一个随机输出的功能,具体代码如下:

 1 public class Solution {
 2     int[] arr;
 3     public Solution(int[] nums) {
 4         arr = new int[nums.length];
 5         for(int i = 0; i < nums.length; i++)
 6             arr[i] = nums[i];
 7     }
 8     
 9     public int pick(int target) {
10         ArrayList<Integer> list = new ArrayList();
11         for(int i = 0; i < arr.length; i++)
12             if(arr[i] == target)
13                 list.add(i);
14         if(list.size() == 0)
15             return -1;
16         else{
17             int random = (int) (Math.random() * list.size());
18             return list.get(random);
19         }
20     }
21 }
22 
23 /**
24  * Your Solution object will be instantiated and called as such:
25  * Solution obj = new Solution(nums);
26  * int param_1 = obj.pick(target);
27  */

 

转载于:https://www.cnblogs.com/zslhq/p/6018407.html

def spatially_regular_gen(): # Generator loop for i in range(num_per_epoch): # Choose the cloud with the lowest probability cloud_idx = int(np.argmin(self.min_possibility[split])) # choose the point with the minimum of possibility in the cloud as query point point_ind = np.argmin(self.possibility[split][cloud_idx]) # Get all points within the cloud from tree structure points = np.array(self.input_trees[split][cloud_idx].data, copy=False) # Center point of input region center_point = points[point_ind, :].reshape(1, -1) # Add noise to the center point noise = np.random.normal(scale=cfg.noise_init / 10, size=center_point.shape) pick_point = center_point + noise.astype(center_point.dtype) # Check if the number of points in the selected cloud is less than the predefined num_points if len(points) < cfg.num_points: # Query all points within the cloud queried_idx = self.input_trees[split][cloud_idx].query(pick_point, k=len(points))[1][0] else: # Query the predefined number of points queried_idx = self.input_trees[split][cloud_idx].query(pick_point, k=cfg.num_points)[1][0] # Shuffle index queried_idx = DP.shuffle_idx(queried_idx) # Get corresponding points and colors based on the index queried_pc_xyz = points[queried_idx] queried_pc_xyz = queried_pc_xyz - pick_point queried_pc_colors = self.input_colors[split][cloud_idx][queried_idx] queried_pc_labels = self.input_labels[split][cloud_idx][queried_idx] # Update the possibility of the selected points dists = np.sum(np.square((points[queried_idx] - pick_po
04-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值