Niuke.com brush questions

ced485cbb11e458d81a746890b32cf3f.gif

Author: Rukawa Maple Knock Code

Blog Homepage: Rukawa Kaede's Blog

Column: Learn java with me

Quote: Stay hungry stay foolish

If you want to do good things, you must first sharpen your tools. Let me introduce you to a super powerful tool for winning offers from big manufacturers - Niuke.com

Click to register for free and brush the questions with me    

Article directory

a string representing a numeric value

replace spaces

Fibonacci sequence

 Number of times a number appears in an ascending array


a string representing a numeric value

Please implement a function to determine whether the string str represents a numerical value (including numbers in scientific notation, decimals and integers).

Numbers in scientific notation (in order) can be divided into the following parts:

1. Some spaces

2. An integer or decimal

3. (optional) an 'e' or 'E' followed by an integer (can be positive or negative)

4. Some spaces

Decimals (in order) can be divided into the following parts:

1. Some spaces

2. (optional) a sign character ('+' or '-')

3. May be one of the following description formats:

3.1 At least one digit followed by a dot '.'

3.2 At least one digit followed by a dot '.' followed by at least one digit

3.3 A dot '.' followed by at least one digit

4. Some spaces

Integers (in order) can be divided into the following parts:

1. Several spaces
2. (optional) a sign character ('+' or '-')

3. At least one digit

4. Some spaces

For example, the strings ["+100","5e2","-123","3.1416","-1E-16"] all represent numeric values.

But ["12e","1a3.14","1.2.3","+-5","12e+4.3"] are not numbers.

hint:

1.1 <= str.length <= 25

2.str contains only English letters (uppercase and lowercase), numbers (0-9), plus sign '+' , minus sign '-' , space ' ' or dot '.' .

3. If you doubt whether the use case can be represented as a numerical value, you can use python's print(float(str)) to check

Advanced: time complexity O(n)\O(n), space complexity O(n)\O(n) 

Ideas:

First trim, remove the spaces at the beginning and end of the string

. can only appear once, and can only appear before e

e can only appear once and should be preceded by a number

+ - can only appear at the beginning or after an e

Spaces, processed with trim, if there is a space in the middle, it will return directly when it fails

Use boolean to indicate whether each situation occurs, only write successful situations

answer:

    public boolean isNumeric (String str) {
     
        str = str.trim();
        //用boolean来表示每一个情况是否出现,是否出现一次(用!XXX来判断)
        boolean numFlag = false, dotFlag = false, eFlag = false, plusFlag = false;
        //只写成功的情况
        for(int i = 0; i < str.length(); i++){
            if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                numFlag = true;
            }else if(str.charAt(i) == '.' && !dotFlag && !eFlag){
                dotFlag = true;
            }else if((str.charAt(i) == 'e' || str.charAt(i) == 'E') &&
                     !eFlag && numFlag){
                eFlag = true;
                //处理132e这种情况
                numFlag = false;
            }else if((str.charAt(i) == '+' || str.charAt(i) == '-') && 
                     (i == 0 || str.charAt(i-1) == 'e' || str.charAt(i-1) == 'E')){
                //什么也不干
            }else {
                return false;
            }
        }
        return numFlag;
    }

replace spaces

Please implement a function that replaces each space in a string s with "%20".

For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.

Data range: 0 \le len(s) \le 1000 \0≤len(s)≤1000 . Ensure that the characters in the string are one of uppercase English letters, lowercase English letters, and spaces.

method one

Idea: first convert the string to a single character

What we want here is to replace the spaces in the string with %20. One way to achieve this is to apply for a temporary array, and then traverse each character of the string. If it is not a space, add the traversed characters to the temporary array. , if it is a space, add 3 characters '%', '2', '0' to the temporary array respectively, and finally convert the temporary array into a string.

    public String replaceSpace(String s) {
        int length = s.length();
        char[] array = new char[length * 3];
        int index = 0;
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                array[index++] = '%';
                array[index++] = '2';
                array[index++] = '0';
            } else {
                array[index++] = c;
            }
        }
        String newStr = new String(array, 0, index);
        return newStr;
    }

Time complexity: O(n), all characters are traversed once
Space complexity: O(n), an array of n*3 is required 

Method Two

Idea: Use StringBuilder

Add each character in the string to StringBuilder one by one, if you encounter a space, replace it with %20

    public String replaceSpace(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ')
                stringBuilder.append("%20");
            else
                stringBuilder.append(s.charAt(i));
        }
        return stringBuilder.toString();
    }

Time complexity: O(n), all characters are traversed once
Space complexity: O(n), the space required by StringBuilder

Fibonacci sequence

Everyone knows the Fibonacci sequence, and now you are required to input a positive integer n, please output the nth item of the Fibonacci sequence.

A Fibonacci sequence is a sequence that satisfies fib(x)=\left\{ \begin{array}{rcl} 1 & {x=1,2}\\ fib(x-1)+fib(x-2) & {x>2}\\ \end{array} \right.fib(x)={1fib(x−1)+fib(x−2)​x=1,2x>2​ array

Data range: 1\leq n\leq 401≤n≤40

Requirements: space complexity O(1)O(1), time complexity O(n)O(n) , this problem also has a time complexity O(logn)O(logn) solution

Enter description:

a positive integer n

Return value description:

Output a positive integer.

method one

Idea: iterative addition (recommended)

The basic idea of ​​the dynamic programming algorithm is: decompose the problem to be solved into several interrelated sub-problems, solve the sub-problems first, and then obtain the solution of the original problem from the solutions of these sub-problems; for the repeated sub-problems, only Solve it when you encounter it for the first time, and save the answer, so that you can directly refer to the answer when you encounter it again, without having to solve it again. Dynamic programming algorithms treat the solution of a problem as the result of a series of decisions

The first and second items of the Fibonacci sequence initialization are both 1, then according to the formula, the 0th item is 0, and it can be accumulated to the nnnth item according to the Fibonacci formula

specific methods:

1: Sequence with less than 2 items, return n directly

2: Initialize item 0, and item 1 is 0, 1 respectively

3: Start from the second item, gradually accumulate according to the formula, and update the summation number to always be the first two items of the next item

public class Solution {
    public int Fibonacci(int n) {
        //从0开始,第0项是0,第一项是1
        if(n <= 1)    
             return n;
         int res = 0;
         int a = 0;
         int b = 1;
         //因n=2时也为1,初始化的时候把a=0,b=1
         for (int i = 2; i <= n; i++){
         //第三项开始是前两项的和,然后保留最新的两项,更新数据相加
             res = (a + b);
             a = b;
             b = res;
         }
        return res;
    }
}

Method Two

idea: recursion

1. When n < 2, return n directly

2. Recursive algorithm: Fibonacci(n-1) + Fibonacci(n-2);

Advantages, the code is simple and easy to write, disadvantages: slow, will time out  Time complexity : O(2^n)  Space complexity : space for recursive stack

public class Solution {
    public int Fibonacci(int n) {
        if (n < 2){
            return n;
        }
        
        return Fibonacci(n-1) + Fibonacci(n-2);
    }
}

 Number of times a number appears in an ascending array

Given a non-descending array of length n and a non-negative integer k, ask to count the number of times k appears in the array

Data range: 0 \le n \le 1000 , 0 \le k \le 1000≤n≤1000, 0≤k≤100, the value of each element in the array meets the requirements of 0 \le val \le 1000≤val≤100
: Space complexity O(1)O(1), time complexity O(logn)O(logn)

Method: Dichotomy (recommended)

Divide and conquer means "divide and conquer", "divide" refers to dividing a large and complex problem into multiple sub-problems with the same nature but smaller scale, and the sub-problems continue to be divided in this way until the problem can be easily solved; ” refers to treating sub-problems individually. After dividing and conquering the sub-problems, the solution of the original problem can be obtained by merging the solutions, so the whole process of dividing and conquering is often implemented by recursion.

Ideas:

Because data is a non-descending array, it is ordered. At this time, we may think of using binary search. But an array may have more than one k, and what we are looking for is not where k appears in the regular dichotomy, but the left bound where k appears and the right bound where k appears. It would be nice if we could just find the positions of numbers that are exactly less than k and the positions of numbers that are just greater than k

And because the array is full of integers, we can consider using binary search to find the position where k+0.5k+0.5k+0.5 should appear and the position where k−0.5k-0.5k−0.5 should appear, and subtract the two is the number of occurrences of k

specific methods:

1: Write a binary search function to find the position of an element in an array. Check the midpoint value of the interval each time, and determine the next interval based on the comparison with the midpoint.

2: Use binary search respectively to find the positions where k+0.5 and k-0.5 should appear. The middle part is all k, and the number of calculations can be subtracted.

public class Solution {
    //二分查找
    private int bisearch(int[] data, double k){ 
        int left = 0;
        int right = data.length - 1;
        //二分左右界
        while(left <= right){ 
            int mid = (left + right) / 2;
            if(data[mid] < k)
                left = mid + 1;
            else if(data[mid] > k)
                right = mid - 1;
        }
        return left;
    }
    public int GetNumberOfK(int [] array , int k) {
        //分别查找k+0.5和k-0.5应该出现的位置,中间的部分就全是k
        return bisearch(array, k + 0.5) - bisearch(array, k - 0.5);
    }
}

Time complexity: O(log2n)O(log_2n)O(log2​n), where nnn is the length of the array, two binary searches, the binary search complexity is O(log2n)O(log_2n)O(log2​n)

Space complexity: O(1)O(1)O(1), constant-level variables, no additional auxiliary space

"The sharing of this issue is here, remember to give the blogger a three-link, your support is the biggest driving force for my creation!

ced485cbb11e458d81a746890b32cf3f.gif

Guess you like

Origin blog.csdn.net/chenchenchencl/article/details/126454644