GESP Level 3 C++ Practice (One-Dimensional Array) luogu-B2093 Find a Specific Value

GESP Level 3 practice, one-dimensional array exercise (Knowledge point 5 in the C++ Level 3 syllabus, one-dimensional array), Difficulty ★☆☆☆☆.

  • GESP Level 3 Practice Question List

  • GESP Level 3 Real Question List

  • GESP Level 3 Syllabus Analysis

luogu-B2093 Find a Specific Value

Problem Requirements

Problem Description

Find a given value in a sequence (starting from index 0) and output the position of its first occurrence.

Input Format

The first line contains a positive integer n, representing the number of elements in the sequence.

The second line contains n integers, each separated by a single space, representing the elements of the sequence. The absolute value of the elements does not exceed 10^9.

The third line contains an integer x, which is the specific value to be searched for. The absolute value of x does not exceed 10^9.

Output Format

If the value x exists in the sequence, output the index of its first occurrence; otherwise, output <span>-1</span>.

Input Output Example #1

Input #1

5
2 3 6 7 3
3

Output #1

1

Problem Analysis

Solution Approach

  1. First, input the length of the array n, then input n integers into the array.
  2. Next, input the specific value x to be searched for.
  3. Start traversing the array from the first element to check if there exists an element equal to x.
  4. If an element equal to x is found, output its index and terminate the program.
  5. If the entire array is traversed without finding an element equal to x, output -1.

Complexity Analysis:

  • The time complexity for inputting n numbers is O(n).
  • The time complexity for traversing the array to find the specific value is O(n).
  • Thus, the total time complexity is O(n).
  • The space complexity is O(n), as it requires storage for n integers in the array.

Example Code

#include <iostream>
using namespace std;
int a[10000];
int main() {
    // Define the array length variable
    int n;
    // Define the number to search for
    int x;
    // Input the array length
    cin >> n;
    // Loop to input n numbers into the array
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    // Input the number to search for
    cin >> x;
    // Traverse the array to find x
    for (int i = 0; i < n; i++) {
        // If x is found, output the index and terminate the program
        if (x == a[i]) {
            cout << i;
            return 0;
        }
    }
    // If not found, output -1
    cout << "-1";
    return 0;
}

For detailed GESP syllabus, real question explanations, knowledge expansion, and practice lists, see:

[Top] [GESP] C++ Certification Learning Resource Summary

The “luogu-” series questions can be evaluated online at Luogu Question Bank.

The “bcqm-” series questions can be evaluated online at Programming Enlightenment Question Bank.

Leave a Comment