1. 程式人生 > >猿圈19年校招筆試題

猿圈19年校招筆試題

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;
}