猿圈19年校招笔试题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014253173/article/details/83069853

1.查找整数

题目描述:

给定一个非降序的整数数组,数组中包含重复数字(重复数字很多),给定任意整数二分查找,返回数组正确的位置,给出函数实现。
a.连续相同的数字,返回最后一个匹配的位置。
b.如果数字不存在返回-1。

输入描述:

第一行给定数组长度n,目标值tar。(1<=n,tar<=10000)
第二行给出n个整数a.

输出描述:

按题目描述输出。

示例:

输入:

7 4
1 2 2 3 4 4 10

输出:

5

题解:

二分查找的变种,在二分查找中添加一点约束条件即可。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;

int Binary_Search(int *a,int n,int key)
{
    int low,high,mid;
    low=1;
    high=n;
    while(low<=high)
    {
        mid=(low+high)/2;
        if(key<a[mid])
            high=mid-1;
        if(key>a[mid])
            low=mid+1;
        else if(key == a[mid]){    //对相同元素的处理
            for(int i=mid; i<=n; i++){
                if(key != a[i])
                    return i-1;
            }
        }

    }
    return -1;
}

int main()
{
    int n,tar,res;
    int a[10005];
    scanf("%d%d",&n,&tar);
    for(int i=0; i<n; i++){
        scanf("%d", &a[i]);
    }
    sort(a,a+n);
    res = Binary_Search(a,n,tar);
    printf("%d\n", res);
    return 0;
}

2.括号的使用:

题目描述:

判断一段文本中()的使用是否是正确的。正确的含义是左右成对,不多不少,如“IS LIUKAN(SH)AN IN (ZHI()HU)” 正确
“()(())(())” 正确
“((LIUKANSHAN(IS HERE((” 不正确
“()((” 不正确

输入描述:

输入一行包含括号的字符串str。(1<=strlen(str)<=1000)

输出描述:

输出True/False

示例:

输入:

IS LIUKAN(SH)AN IN (ZHI()HU)

输出:

True

题解:

简单的括号匹配,用栈模拟。

#include <iostream>
#include <cstring>
#include <string>
#include <stack>
using namespace std;
int main()
{
    char str[1005];
    cin >> str;
    int len = strlen(str);
    stack<char> s;
    int i;
    int cnt = 0;
    for (i = 0; i < len; i++) {
        if (str[i] == '(') {
            s.push(str[i]);
            ++cnt;
            continue;
        }
        if (str[i] == ')') {
            ++cnt;
            if (!s.empty() && s.top() == '(') {
                s.pop();
                continue;
            }
        }
    }

    if (!s.empty()) {
        cout<<"False"<<endl;
    }
    if (cnt % 2 != 0) {
        cout<<"False"<<endl;
    }else{
      cout<<"True"<<endl;
    }
    return 0;
}

3.走楼梯

题目描述:

现在有一截楼梯,根据你的腿长,你一次能走1级或2级楼梯,已知你要走n级楼梯才能走到你的目的楼层,请实现一个方法,计算你走到目的楼层的方案数。

输入描述:

输入整数n。(1<=n<=50)

输出描述:

输出方案数。

示例1

输入:

5

输出:

8

题解:

简单的斐波那契数列。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
using namespace std;

long long Fib(int N)
{
    long long first = 1;
    long long second = 2;
    long long ret = 0;
    for(int i = 3; i <=N; i++)
    {
        ret = first + second;
        first = second;
        second = ret;
    }
    return second;
}
int main()
{
    int n;
    long long res;
    while(cin >> n){
      res = Fib(n);
      cout << res << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014253173/article/details/83069853
今日推荐