今日头条2018秋招编程题

今日头条 2018秋招 Android方向 编程题


1、手串

作为一个手串艺人,有金主向你订购了一条包含n个杂色串珠的手串–每个串珠要么无色,要么涂了若干种颜色。为了使手串的色彩看起来不那么单调,金主要求,手串上的任意一种颜色(不包含无色),在任意连续的m个串珠里至多出现一次(注意:手串是环形)。手串上的颜色一共有c种。现在按顺时针序告诉你n个串珠的手串上,每个串珠用所包含的颜色分别有哪些。请你判断该手串上有几种颜色不符合要求。即询问有多少种颜色在任意连续m个串珠中出现了至少两次。
输入描述:
第一行输入n,m,c,用空格隔开。(1<=n <= 10000, 1<=m<=1000,1<=c<=50),接下来n行,每行的第一个数num(0<=num<=c)表示第i颗珠子有几种颜色,接着是num个数字,每个数字x表示第i颗珠子包含第x种颜色。
输出描述:
一个非负整数,表示该手串上有几种颜色不符合要求。

示例:

输入:
5 2 3
3 1 2 3
0
2 2 3
1 2
1 3
输出:
2
解释:
第一种颜色出现在:1,符合要求
第二种颜色出现在:1,3,4,3和4相邻,不符合
第三种颜色出现在:1,3,5,5和1是相邻的,因此不符合。
所以有2种颜色不符合要求。

解析:

用二维数组colors[][],记录每种颜色,出现在哪些珠子上。
首先,先遍历每个珠子,将每种颜色出现在第几个珠子上记录到colors数组中。
对于colors中的每一种颜色,
判断其内珠子是否存在m相邻的情况,比如m=3,1和3算相邻,1和4不相邻。
这里要注意手串是环形的,需要处理特殊情况。
具体见代码。

C++代码实现:

#include <iostream>
#include <vector>
using namespace std;

int findColors(int n, int m, int c,const vector<vector<int>>& colors)
{
    if(m==1)
        return 0;
    vector<vector<int>> colorIndex(c);
    int count = 0, i=0,j=0;
    for(; i<n; i++){
        count = colors[i].size();
        for(j=0; j<count; j++){
            colorIndex[colors[i][j]-1].push_back(i+1);
        }
    }

    int result=0;
    for(i=0; i<c; i++){
       count = colorIndex[i].size();
       if(count<=1)
            continue;
       for(j=0; j<count-1; j++){
            //查找是否存在m相邻的珠子
          auto it = lower_bound(colorIndex[i].begin(),colorIndex[i].end(),colorIndex[i][j]+1);
          if(it!=colorIndex[i].end() && *it-colorIndex[i][j] < m){
             result++;
             break;
          }
       }
       if(j==count-1 && (colorIndex[i][j]+1)%n == colorIndex[i][0]){  //手串是环形的,特殊情况
            result++;
       }
    }
    return result;
}

int main()
{
    int n,m,c,t,k;
    cin>>n>>m>>c;
    vector<vector<int>> colors;
    for(int i=0; i<n; i++){
        cin>>t;
        vector<int> color;
        for(int j=0; j<t; j++){
            cin>>k;
            color.push_back(k);
        }
        colors.push_back(color);
    }
    cout<<findColors(n,m,c,colors);
}

2、文章喜好

给定n个头条用户对某类文章的喜好度,查找用户对某类文章的喜好度为q的人数。输入q行数,每行数为l,r,k,表示在[l,r]范围内用户对某类文章的喜好度为k。每行输出对应的人数。

示例:

输入:
5
1 2 3 3 5 (表示5个用户对某类文章的喜好度)
3
1 3 2
2 4 3
3 5 5
输出:
1 (1到3号用户中,只有用户2的喜好度为2)
2(2到4号用户中,用户3和4的喜好度为3)
1(3到5号用户中,只有用户5喜好度为5)

c++代码实现:

void query(int n,int *users,int q,int questions[][3])
{
    int cnt;
    for(int i=0; i<q; i++){
        cnt = 0;
        for(int j=questions[i][0]; j<=questions[i][1]; j++){
            if(users[j-1]==questions[i][2])
            cnt++;
        }
        cout<<cnt<<endl;
    }
}

int main()
{
    int n;
    cin>>n;
    int users[n];
    for(int i=0; i<n; i++)
        cin>>users[i];
    int q;
    cin>>q;
    int questions[q][3];
    for(int i=0; i<q; i++)
        cin>>questions[i][0]>>questions[i][1]>>questions[i][2];
    query(n,users,q,questions);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/peaktravel/article/details/77925653
今日推荐