C语言找出奇艺的3位数,2020.09.13爱奇艺秋招笔试(3道简单编程题AK)

第二题:AC给一个长度文n的整数数组,其中有一个元素出现了超过n次,求出该元素

思路:直接计数,用cnt记录次数,val记录出现cnt次的元素,遍历时判断相等就++cnt, 不相等就--,

--cnt后如果 = 0,就更新元素,最后直接输出val即可

代码:

#include

using namespace std;

int main(void)

{

#ifndef ONLINE_JUDGE

freopen("b.txt", "r", stdin);

#endif

int n = 0;

int x;

string s;

while(getline(cin, s)) {

stringstream ss(s);

vector a;

while (ss >> x) a.push_back(x);

int val = a[0];

int cnt = 1;

for(int i = 1; i 

if(a[i] == val) ++cnt;

else {

--cnt;

if(cnt == 0) {val = a[i]; cnt = 1;}

}

}

cout <

}

return 0;

}

第三题:AC给一个整数序列,求出该序列中满足 a + b + c = 0 的元组的序列,每个答案一行

思路:这个题当然可以直接采取暴力检索,如果长度为n,时间复杂度为O(N^3) ,判断如果元素超过1000个就会超时,

所以考虑降维,复杂度降到O(N^2),因为有 a + b + c = 0, 变成 a + b = -c, 也就是,只需要枚举 (a+b) 和 -c 即可,

先从小到达排序原数组,然后从第一个>= 0 位置(记为:r )的-c开始往右枚举,在-c的左边(区间为:[0, r-1] )查找 a + b = -c的元组,

每次枚举r时,检索[0, r-1] 最多需要r次,所以最后总的时间复杂度O(N * (N-1) / 2),一次AC, 耗时0ms

代码:

#include

using namespace std;

#define ios ios::sync_with_stdio(false),cin.tie(0);

using pii = pair;

const int maxn = 10005;

int a[maxn];

int n;

vector getSum(int l, int r, int val) {

vector ans;

while(l 

if(a[l] + a[r] > val) r--;

else if(a[l] + a[r] 

else {

ans.push_back({a[l], a[r]});

while(l 

while(l 

l++;

r--;

}

}

return ans;

}

int main(void)

{

#ifndef ONLINE_JUDGE

freopen("c.txt", "r", stdin);

#endif

string s;

while(getline(cin, s)) {

stringstream ss(s);

n = 0;

int x;

while(ss >> x) a[n++] = x;

sort(a, a+n);

set> ans;

int r = 0;

while(r 

for(; r 

vector segs = getSum(0, r-1, -a[r]);

if(segs.size() == 0) continue;

for(auto& p : segs) ans.insert({p.first, p.second, a[r]});

}

for(auto& v : ans) {

cout <

}

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值