[force buckle question type summary and template] sword finger offer 1 - array and string

Posted by cloudnyn3 on Mon, 21 Feb 2022 03:59:30 +0100

Question type summary

subjectsummarypracticekey word
Find in 2D arrayIn an n * m two-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete an efficient function, input such a two-dimensional array and an integer, and judge whether the array contains the integer.Starting from the upper right corner, go to the left when you are bigger than the target, and go down when you are smaller than the targetArray traversal
Print from 1 to maximum n digitsEnter the number N and print out the decimal number from 1 to the maximum n digits in sequence. For example, if you enter 3, 1, 2 and 3 will be printed up to the maximum 3 digits 999.one ⃣ Multiply [1,2,3,4,5,6,7,8,9] by 10 and add this array. If the array starts with 0, it will cycle as many times as many bits are needed ⃣ ⒆ concatenate with strings, and the last bit is incremented from 0 to 9 ⚠️ It is possible to investigate the problem of large number calculationArray traversal
Build product arrayGiven an array A[0,1,..., n-1], please construct an array B[0,1,..., n-1], where the element B[i]=A[0] in B × A[1] ×…× A[i-1] × A[i+1] ×…× A[n-1]. Division cannot be used.Divide into upper and lower triangular matrices and maintain a tmp multiplied from the tip of the triangle to the bottomArray traversal
Print matrix clockwiseEnter a matrix and print out each number in clockwise order from the outside to the inside.Define the upper, lower, left and right boundaries, loop through the entire array, and then nest four loops in the loop, from left to right, from top to bottom, from right to left, and from bottom to top. Traverse the entire array according to the meaning of the question and control the boundary.Loop + attention boundary
Replace spacesPlease implement a function to replace each space in the string s with "% 20"StringBuilder, s.charAt traversal, not the space is append, but the space is replaced with "% 20"String traversal
II. Left rotation stringThe left rotation operation of a string is to transfer several characters in front of the string to the end of the string. Please define a function to realize the function of string left rotation operation. For example, if you enter the string "abcdefg" and the number 2, the function will return the result "cdefgab" obtained by rotating the left two digits.At the original string, traverse backward from the position n that needs to be reversed and save it to the result string, then traverse from the initial position of the original string to position n and continue to add it to the result stringString traversal or substring splicing
Shunzi in playing cardsDraw five cards at random from playing cards to judge whether they are a surplus, that is, whether these five cards are continuous. 2 ~ 10 is the number itself, a is 1, J is 11, Q is 12, K is 13, and DA and Xiao Wang are 0, which can be regarded as any number. A cannot be regarded as 14.You need to sort the array in ascending order; If there is duplicate data in the array, false is returned; Make minVal the minimum value excluding the king of size. If maxval minVal > 5, false will be returnedArray sort arrays sort()
Minimum number of rotation arrayMoving the first elements of an array to the end of the array is called array rotation. Enter a rotation of an incrementally sorted array and output the smallest element of the rotation array. For example, if the array [3,4,5,1,2] is a rotation of [1,2,3,4,5], the minimum value of the array is 1.Binary search to determine whether the condition is that mid is greater than rightSorting - bisection
Arrange the array into the smallest numberInput an array of non negative integers, put all the numbers in the array together to form a number, and print the smallest of all the numbers that can be spliced.Change the rules in the fast sorting: if the splicing string x + Y > y + X, the value x > y🌟 Sort - quick sort
Adjust the array order so that odd numbers precede even numbersEnter an integer array and implement a function to adjust the order of numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array.First, specify the front pointer start and the rear pointer end. Then, the front pointer locates the even number and the rear pointer locates the odd number. After positioning, exchange the two values until the array traversal is completedDouble pointer
And are two numbers of sEnter an incrementally sorted array and a number s, and find two numbers in the array so that their sum is exactly s. If the sum of multiple pairs of numbers is equal to s, any pair can be output.If there is no sorting, you need to sort first. Double pointer, larger right pointer –, smaller left pointer –Double pointer
1. Flip word orderInput an English sentence and flip the order of words in the sentence, but the order of characters in the word remains the same. For simplicity, punctuation is treated like ordinary letters. For example, enter the string "I am a student.", "student. a am I" is output.First remove the extra spaces at the beginning and end, traverse from back to front, lock the words through the front and back pointers, skip the middle space, and finally reverse the words in the whole sentenceDouble pointer
Continuous positive sequence with sum sEnter a positive integer target, and output a sequence of consecutive positive integers with a sum of target (at least two numbers)Use the sliding window, set the left and right pointers, maintain a sub array from the starting position as the window, and judge whether the window is summed to target. If yes, add the result. If it is less than target, the window moves to the right, and if it is greater than target, the window moves to the left🌟 sliding window
A number (mode) that appears more than half the time in the arrayA number in the array appears more than half the length of the array. Please find this number.one ⃣ Array sort - > num [mid] O (nlogn) 2 ⃣ Hash count - > traversal O(n) 3 ⃣ Molar voting: traverse the num array, count with count, and record the current number as cur. If the traversed num is equal to cur, the count will increase automatically, otherwise it will decrease automatically. When it decreases to 0, the cur will be modified to the currently traversed num. by increasing or decreasing, the effect that the remaining number is the result will be achieved in the end, and the time complexity is O(n)🌟 Moore vote
1. Find a number in a sorted arrayCounts the number of times a number appears in the sorted array.(if the array is not sorted, it should be sorted first) find the right boundary of target and target-1 in bisection, and subtract themBinary search
Missing numbers from 0 to n-1All numbers in an incrementally sorted array with a length of n-1 are unique, and each number is in the range of 0 ~ n-1. Among the N numbers in the range 0 ~ n-1, there is only one number that is not in the array. Please find this number.The missing number is equal to the index corresponding to the "first element of the right subarray", so consider using dichotomy to find the "first element of the right subarray". Left subarray: nums[i] == i right subarray: nums [i]= iBinary search
Convert string to integerWrite a function StrToInt to realize the function of converting string into integer. atoi or other similar library functions cannot be used. ⭕ Firstly, the function will discard useless leading space characters as needed until the first non space character is found. ⭕ When the first non empty character we find is a positive or negative sign, combine the symbol with as many consecutive numbers as possible as the sign of the integer; If the first non null character is a number, it is directly combined with subsequent consecutive numeric characters to form an integer. ⭕ In addition to the valid integer part of the string, there may also be redundant characters. These characters can be ignored and should not affect the function. ⭕ Note: if the first non white space character in the string is not a valid integer character, the string is empty, or the string contains only white space characters, your function does not need to be converted. ⭕ In any case, if the function cannot perform effective conversion, please return 0. Note: assuming that our environment can only store 32-bit signed integers, the range of values is [− 231, 231 − 1]. If the value exceeds this range, please return INT_MAX (231 − 1) or INT_MIN (−231) . trim() remove spaces - > judge signs - > convert characters to numbers C -'0 '- > handle non numeric situations - > handle large numbers, res and integer MAX_ Value / 10 comparison to determine whether it is out of range. If it exceeds 2147483647, it will return directly ⚠️ Do not use integer MIN_VALUE, he can't directly change * - 1 into - MIN_VALUELarge number processing



  1. Define int mid = left + (right - left)/2; (prevent large number overflow)
  2. Left and right are array left and right
  3. When the left pointer is less than or equal to the right pointer - > if (judge the condition of looking left and right) - > look left = mid + 1 in the next step;, Find right = mid - 1 to the right;

Quick row

Fast exhaust interpretation - CSDN

  1. Find benchmark element: the first bit of the incoming array is used as the benchmark element, with double pointers at the beginning and end (sorted from large to small). The left pointer finds the one smaller than the benchmark element, the right pointer finds the one larger than the benchmark element, exchanges the position, and finally returns the index of the split point.
  2. Recursive call. When left < right, the left / right array is quickly arranged.
public class QuickSort {
    private static void quickSort(int[] array, int startIndex, int endIndex) {
        if (startIndex < endIndex) {
            // Find base element
            int baseIndex = divide(array, startIndex, endIndex);
            // Recursive call to quickly sort the left array after separation
            quickSort(array, startIndex, baseIndex - 1);
            // Recursive call to quickly sort the right array after separation
            quickSort(array, baseIndex + 1, endIndex);
        } else {

     * Separating arrays by double-sided loop method
     * @param array      Array to be sorted
     * @param startIndex Start subscript of array
     * @param endIndex   End subscript of array
     * @return Returns the location of the separation point
    private static int divide(int[] array, int startIndex, int endIndex) {
        // Use the first element of the array as the starting element
        int base = array[startIndex];
        int i = startIndex;
        int j = endIndex;
        while (i != j) {
            // Find the first value less than the reference number from right to left
            while (i < j && array[j] > base) {
            // Find the first value greater than the reference number from left to right
            while (i < j && array[i] <= base) {
            // change of position
            if (i < j) {
                swap(array, i, j);

        // Pointer i meets pointer j and exchanges the position of the element at the coincidence point with the reference element
        array[startIndex] = array[i];
        array[i] = base;

        // Returns the location of the separation point
        return i;

    // Exchange values of i and j positions
    private static void swap(int[] array, int i, int j) {
        int temp;
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;

sliding window

class Solution {
    public int[][] findContinuousSequence(int target) {
        int left = 1;
        int right = 2;
        List<int[]> res = new ArrayList<>();

        while (left < right) {
            int sum = (left + right) * (right - left + 1) / 2;
            if (sum == target){
                int[] arr = new int[right - left + 1];
                for (int k = left; k <= right; k++) {
                    arr[k - left] = k;
            else if (sum < target) {
            else {

        return res.toArray(new int[res.size()][]);

Example answer

Print matrix clockwise

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length == 0) return new int[0];
        int left = 0, right = matrix[0].length - 1, top = 0, bottom = matrix.length - 1, x = 0;
        int[] res = new int[(right + 1) * (bottom + 1)];
        while(true) {
            for(int i = left; i <= right; i++) res[x++] = matrix[top][i];
            if(++top > bottom) break;
            for(int i = top; i <= bottom; i++) res[x++] = matrix[i][right];
            if(left > --right) break;
            for(int i = right; i >= left; i--) res[x++] = matrix[bottom][i];
            if(top > --bottom) break;
            for(int i = bottom; i >= top; i--) res[x++] = matrix[i][left];
            if(++left > right) break;
        return res;

Moore vote

class Solution {
    public int majorityElement(int[] nums) {
        int cur = 0;
        int count = 0;
        for(int num : nums){
            if(count == 0) {
                cur = num;
            if(num == cur) {
            } else {
        return cur;

Quick row

    public String minNumber(int[] nums) {
        String[] strs = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            strs[i] = String.valueOf(nums[i]);
        quickSort(strs, 0, strs.length - 1);
        StringBuilder res = new StringBuilder();
        for (String s : strs)
        return res.toString();

    public void quickSort(String[] strs, int low, int high) {
        if (low < high) {
            int middle = getMiddle(strs, low, high);
            quickSort(strs, low, middle - 1);
            quickSort(strs, middle + 1, high);

    public int getMiddle(String[] strs, int low, int high) {
        //The first number of the array is the base element
        String temp = strs[low];
        while (low < high) {
            //Find a number smaller than the benchmark from back to front
            while (low < high && (strs[high] + temp).compareTo(temp + strs[high]) >= 0)
            //Move the number smaller than the benchmark to the low end
            strs[low] = strs[high];
            //Find a number larger than the benchmark from front to back
            while (low < high && (strs[low] + temp).compareTo(temp + strs[low]) <= 0)
            //Move numbers larger than the benchmark to the high end
            strs[high] = strs[low];
        strs[low] = temp;
        return low;

Large number processing

class Solution {
    public int strToInt(String str) {
        char[] c = str.trim().toCharArray();
        if(c.length == 0) return 0;
        int res = 0, boundry = Integer.MAX_VALUE / 10;
        int start = 1, sign = 1;
        if(c[0] == '-') sign = -1;
        else if(c[0] != '+') start = 0;
        for(int i = start; i < c.length; i++) {
            if(c[i] < '0' || c[i] > '9') break;
            if(res > boundry || res == boundry && c[i] > '7') return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            res = res * 10 + (c[i] - '0');
        return sign * res;

Topics: Algorithm leetcode string array