真题链接:https://www.nowcoder.com/test/8537269/summary

第一题:

 1 #include"iostream"
 2 #include"algorithm"
 3 #include"stdio.h"
 4 using namespace std;
 5 const int MAXN=300005;
 6 struct node
 7 {
 8     int value;
 9     int index;
10 };
11 node users[MAXN];
12 int  n,q;
13 
14 bool Cmp(const node &a,const node &b)
15 {
16     if(a.value!=b.value)
17         return a.value<b.value;
18     return a.index<b.index;
19 }
20 
21 int BinarySearch(int l,int r,int k)
22 {
23     while(l<=r)
24     {
25         int mid=(l+r)/2;
26         if(users[mid].value==k)
27             return mid;
28         if(users[mid].value<k)
29             l=mid+1;
30         else
31             r=mid-1;
32     }
33     return -1;
34 }
35 
36 int CountKInRange(int l,int r,int k)
37 {
38     int kIndex=BinarySearch(1,n,k);
39     if(kIndex==-1)
40         return 0;
41     int result=0,tempIndex=kIndex;
42     while(tempIndex>=1&&users[tempIndex].value==k)
43     {
44         if(users[tempIndex].index>=l&&users[tempIndex].index<=r)
45             result++;
46         tempIndex--;
47     }
48     tempIndex=kIndex+1;
49     while(tempIndex<=n&&users[tempIndex].value==k)
50     {
51         if(users[tempIndex].index>=l&&users[tempIndex].index<=r)
52             result++;
53         tempIndex++;
54     }
55     return result;
56 }
57 int main()
58 {
59     while(scanf("%d",&n)==1)
60     {
61         for(int i=1;i<=n;i++)
62         {
63             scanf("%d",&users[i].value);
64             users[i].index=i;
65         }
66         sort(users+1,users+1+n,Cmp);
67 
68 //        for(int i=1;i<=n;i++)
69  //           cout<<users[i].value<<' '<<users[i].index<<endl;
70         cin>>q;
71         int l,r,k;
72         while(q--)
73         {
74             scanf("%d%d%d",&l,&r,&k);
75             cout<<CountKInRange(l,r,k)<<endl;
76         }
77     }
78     return 0;
79 }
View Code

相关文章:

  • 2021-06-24
  • 2021-05-15
  • 2021-10-07
  • 2022-01-09
  • 2021-11-10
  • 2022-12-23
  • 2021-05-06
  • 2021-06-12
猜你喜欢
  • 2021-11-09
  • 2021-07-22
  • 2021-06-15
  • 2021-05-17
  • 2021-06-13
  • 2021-09-02
  • 2021-04-28
相关资源
相似解决方案