0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語 ALDS1_4_B Binary Search

Posted at

問題

コード

# include <stdio.h>

int A[1000000],N;

int binary_search(int key){
    int left = 0;
    int right = N;
    int mid;

    while(left < right){
        mid = (left + right) / 2;
        if (key == A[mid])
            return 1;
        if (key > A[mid])
            left = mid + 1;
        else if (key < A[mid])
            right = mid;
    }
    return 0;
}

int main(void)
{
    int i, q, key, count = 0;
    
    scanf("%d", &N);
    for(i = 0; i < N; i++)
        scanf("%d", &A[i]);

    scanf("%d", &q);
    for(i = 0; i < q; i++){
        scanf("%d", &key);
        if (binary_search(key))
            count++;
    }
    printf("%d\n", count);

    return 0;
}

ポイント

  • データのキーが整列されているときしか使えない

所感

  • 途中別のことしてた。スクリーンタイム使わないと。

所要時間:30分

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?