题目大意:一个数组,选定数组中一个数x,每次可以删掉不包含x的一段,使得最终数组只剩下x,求最小的删除次数。

可以将一段连续相同的数看成一个数字,然后记录它的出现次数。最小值就是出现次数+1。特例:该数出现在数组开头或结尾,这两种情况每次出现都要-1。

code1

#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
const int N = 2e5 + 10;
int a[N];
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        for(int i = 1; i <= n; i++) cin >> a[i];
        map<int, int> mp;
        for(int i = 1; i <= n; i++)
        {
            if(a[i] == a[i - 1]) continue;
            mp[a[i]]++;
        }
        mp[a[1]]--;	// 出现在开头
        mp[a[n]]--;	// 出现在结尾
        int res = n;
        for(int i = 1; i <= n; i++)
        {
            res = min(mp[a[i]] + 1, res);
        }
        cout << res << endl;
    }
}

code2

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
int main()
{
    cin.tie(nullptr);
    int t;
    cin >> t;
    while(t--)
    {
        int n;
        cin >> n;
        vector<int> a(n);
        for(auto& x : a) cin >> x;
        a.erase(unique(a.begin(), a.end()), a.end()); // stl 去重
        map<int, int> mp;
        n = a.size();
        for(auto x : a) mp[x]++;
        int res = n;
        for(auto& x : a)
        {
            res = min(res, mp[x] + 1 - (a[0] == x) - (a[n - 1] == x));
        }
        cout << res << endl;
    }
}

相关文章:

  • 2022-12-23
  • 2021-06-04
  • 2022-12-23
  • 2022-01-07
  • 2021-04-23
  • 2021-06-22
  • 2021-06-10
  • 2022-12-23
猜你喜欢
  • 2021-07-17
  • 2022-01-10
  • 2021-09-25
  • 2021-03-30
  • 2021-11-08
  • 2020-05-15
相关资源
相似解决方案