leetcode1906 查询差绝对值的最小值

思路:

注意到数组a中元素的取值范围只有1-100,可以通过枚举1-100中每个数字是否出现的方式来计算。具体可以通过前缀和实现。

实现:

 1 class Solution
 2 {
 3 public:
 4     vector<int> minDifference(vector<int>& nums, vector<vector<int>>& queries)
 5     {
 6         vector<int>res;
 7         int n = nums.size();
 8         vector<vector<int>> sum(n + 1, vector<int>(101, 0));
 9         for (int i = 0; i < n; i++)
10         {
11             for (int j = 1; j <= 100; j++)
12             {
13                 sum[i + 1][j] = sum[i][j];
14             }
15             sum[i + 1][nums[i]]++;
16         }
17         for (int i = 0; i < queries.size(); i++)
18         {
19             int l = queries[i][0], r = queries[i][1];
20             vector<int> v;
21             for (int j = 1; j <= 100; j++)
22             {
23                 int x = sum[r + 1][j] - sum[l][j];
24                 if (x) v.push_back(j);
25             }
26             int minn = 100;
27             for (int j = 0; j < v.size() - 1; j++)
28             {
29                 minn = min(minn, v[j + 1] - v[j]);
30             }
31             if (minn == 100) res.push_back(-1);
32             else res.push_back(minn);
33         }
34         return res;
35     }
36 }

leetcode1906 查询差绝对值的最小值

上一篇:类的static成员函数与普通成员函数的区别


下一篇:EureKa环境初步搭建