Daily quiz-2

Table of contents

1. Multiple choice questions

2. Programming questions

1. Invert the string

2. Sort subsequences

3. Find the longest consecutive number string in the string

4. Numbers that appear more than half the time in the array



1. Multiple choice questions

1、

Question analysis:

The general form of two-dimensional array initialization is:

Data type array name [constant expression 1] [constant expression 2] = {initialization data};

Among them, constant expression 1 and constant expression 2 represent the number of rows and columns of the array respectively. The initialization data is enclosed in curly braces. The data in each row is separated by commas. A semicolon can be added at the end of each row. If the number of initialization data is less than the number of elements of the array, the remaining elements will be automatically assigned a value of 0. If constant expression 1 is omitted, the compiler will automatically infer the number of rows in the array based on the number of initialization data. If constant expression 2 is omitted, the compiler will report an error. Therefore the answer is B.

2、

Question analysis: (1) Use the return statement to return a structure or array containing multiple values;

(2) Use pointers or references as formal parameters of functions, and return multiple values ​​by modifying the variables pointed to by the pointers or references ;

(3) Use static variables or global variables to store multiple return values, and then access them in the calling function.

Among them, the first method and the second method are more common and recommended , because they can ensure the encapsulation and reusability of functions, and can also avoid potential errors and conflicts. The third method is not recommended because it will destroy the encapsulation and reusability of the function, and will also increase the complexity and maintenance cost of the program.

3、

Question analysis: int *p[4]. is an array of pointers. It represents an array containing 4 elements. Each element is a pointer to type int. Since "[]" has a higher priority than "*", p is first combined with "[]" and then with "*" , so the answer is C.

4、

Question analysis: The long long type occupies 8 bytes on a 32-bit machine, which is 64 bits 1; little endian means that the low-order byte is stored at a low address and the high-order byte is stored at a high address. When the printf function prints a long long type variable, it divides the 8 bytes of the variable into two 4-byte parts , then reads the first part from the low address, and then reads the second part part. Each part can be regarded as a number of type int. Therefore, the value of variable a is 1, and the storage method in memory is 01 00 00 00 00 00 00 00 , where 01 is the low-order byte and is stored at the low address. When the printf function prints a, it will read 4 bytes starting from the low address, which is 01 00 00 00, which is converted to decimal 1. Note that there are still 4 bytes of a that have not been read at this time . When printing b, the value of variable b is 2, and the storage method in the memory is 02 00 00 00 00 00 00 00, where 02 is the low-order word section, stored at a low address. When the printf function prints b, it will read 4 bytes starting from the low address, which is 02 00 00 00, but because of the previous 4 bytes, 02 becomes the fifth byte, so print It comes out as 0 . The value of variable c is 3, and the storage method in memory is 03 00 00 00 00 00 00 00, where 03 is the low-order byte and is stored at the low address. When the printf function prints c, it will read 4 bytes starting from the low address, which is 03 00 00 00, which is 2 when converted to decimal. This is because 03 is the 9th byte, not the first byte, so its weight is 2.

2. Programming questions

1. Invert the string

Analysis question: First reverse the entire string, then traverse the string, find each word, and reverse the word. Here we use reverse in the stl algorithm, so an iterator is used to traverse the string.

code show as below:

#include <iostream>
#include<string>
#include<algorithm>
using namespace std;

int main() {
    string str;
    while (getline(cin, str)) {
        reverse(str.begin(), str.end()); //整体逆置
        auto start = str.begin();
        while (start != str.end()) {
            auto end = start;
            while (*end != ' ' && *end != '\0') {
                end++;
            }
            reverse(start, end);
            if (end != str.end())
                start = end + 1;
            else
                start = end;
        }
        cout << str << endl;
    }

}

Knowledge point: The begin() function returns an iterator pointing to the first element of the string. For example, if there is a string str= "He11o";, then str.begin() points to the character 'H'. The end() function returns an iterator pointing to the end of the string (the position next to the last character). For example, if there is a string str = "Hello";, then str.end() points to the '\0' null character, which is the end mark of the string. The scope of these two functions is left-closed and right-open, that is, they include the first element of the string but not the last element .

The scope of the reverse function is left-closed and right-open , that is, it includes the element pointed to by start, but does not include the element pointed to end. This range can be expressed using square brackets as [start, end). For example, if there is an array int arr [] = (1, 2, 3, 4, 5};, then reverse (arr + 1, arr + 4); will flip the area of ​​array index [1, 4), also It is the three elements 2, 3, 4. The flipped array becomes {1, 4, 3, 2, 5}.

2. Sort subsequences

Question analysis: Non-decreasing means a[i]<=a[i+1], decreasing means a[i]>a[i+1], non-increasing means a[i]>=a[i+1], increasing That is a[i]<a[i+1].

  • First, we need to define a flag variable to record the current sorting status, with an initial value of 0. If the flag is 0, it means that the sorting status has not been determined; if the flag is 1, it means that the current sorting is non-descending; if the flag is -1, it means that the current sorting is non-increasing.
  • Then, we traverse the array A and compare the size relationship between two adjacent elements. If A[i] < A[i+1], it means that the current order is ascending; if A[i] > A[i+1], it means that the current order is descending; if A[i] == A[i+1], Indicates that there are currently no changes.
  • Next, we determine whether we need to split the subsequence based on the value of the flag and the current size relationship. If flag is 0, it means that the sorting status has not been determined, then we update the flag value based on the current size relationship and do not need to split the subsequence. If the flag is 1, it means that the current sorting is non-descending, then we determine whether the current order is descending. If it is descending order, then we need to divide the subsequence and update the flag value to -1; if it is not descending order, then we do not Need to split into subsequences. If the flag is -1, it means that the current sorting is non-increasing, then we determine whether the current order is ascending. If it is ascending order, then we need to divide the subsequence and update the flag value to 1; if it is not ascending order, then we do not Need to split into subsequences.
  • Finally, we count the number of divided subsequences, which is the answer that can at least divide the array A into several sorted subsequences.
  • code show as below:
#include <iostream>
#include<vector>
using namespace std;

int main() {
    int n = 0;
    while (cin >> n) {
        vector<int> list;
        int count = 1;
        int flag = 0;
        list.resize(n);
        for (int i = 0; i < n; i++) {
            cin >> list[i];
        }
        for (int i = 0; i < n - 1; i++) {
            if (flag == 0) 
            {
                if (list[i] == list[i + 1])continue;
                else if (list[i] < list[i + 1])
                flag = 1;
                else 
                flag = -1;
            } 
            else if (flag == 1) 
            {
                if (list[i] > list[i + 1]) 
                {
                    count++;
                    flag = 0;

                }

            } else 
            {
                if (list[i] < list[i + 1])
                {
                    count++;
                    flag = 0;
                }
            }
        }
        cout << count << endl;
    }
}

3. Find the longest consecutive number string in the string

Problem analysis: Traverse the string and use cur to record the continuous numeric string. If a non-numeric character is encountered, it means that a continuous numeric string has ended. Then compare the numeric string with the previous numeric string. If it is longer, update it. Longer digit strings are updated to res.

#include <iostream>
#include<string>
#include<algorithm>

using namespace std;

int main() {
    string str, res, cur;
    cin>>str;

    for (int i = 0; i < str.length()+1; i++) 
    {
        if (str[i] >= '0' && str[i] <= '9') 
        {
            cur += str[i];
        } 
        else {// 找出更长的字符串,则更新字符串

            if (res.size() < cur.size())
                res = cur;
            else
                cur.clear();
        }
    }
    cout<<res;

}

4. Numbers that appear more than half the time in the array

Topic analysis:

Idea 1: After the array is sorted, if a number that meets the conditions exists, it must be the number in the middle of the array . Although this method is easy to understand, since it involves quick sort, its time complexity is O(NlogN) and is not optimal;

lass Solution {
  public:
    int MoreThanHalfNum_Solution(vector<int>& numbers) {

        sort(numbers.begin(), numbers.end());
        int middle = numbers[numbers.size() / 2];
        int count = 0; // 出现次数
        for (int i = 0; i < numbers.size(); ++i) {
            if (numbers[i] == middle) ++count;
        }
        return (count > numbers.size() / 2) ? middle : 0;

    }
};

Idea 2: It is the number that appears more than half the length of the array.
If the two numbers are not equal, eliminate these two numbers. In the worst case, one mode and one non-mode are eliminated each time. Then if there is a mode, The last number left must be the mode.

class Solution {
  public:
    int MoreThanHalfNum_Solution(vector<int>& numbers) 
    {
        int times=1;
        int result=numbers[0];
        for(int i=1;i<numbers.size();i++)
        {
            if(numbers[i]!=result)
            {
                if(times==0)
                {
                    result=numbers[i];
                }
                else
                 {
                times--;
                }   
            }
            else {
                times++;
                result=numbers[i];
            
            }
        }
return result;
    }
};

Guess you like

Origin blog.csdn.net/weixin_65592314/article/details/132722246