(The latest version 2022 version) Jianzhi offer search algorithm solution


1. Search in the JZ4 two-dimensional array of "Jianzhi offer"

Title description:

insert image description here

Problem-solving ideas:

Idea:
Observe the array in the upper right corner of the matrix. The number is the minimum value of the current column and the minimum value of the current row, that is, the middle value of the number from row to column, so the idea of ​​binary search can be used.

  • Starting from the upper right corner, first check the number in the upper right corner, if the number is equal to the number you want to find, the search process ends.
  • If the current number is greater than the target, remove the column where the number is located, and the target will only appear on the row, because the numbers in this column will be greater than the target.
  • If the current number is smaller than the target, the row where the number is located is eliminated, and the column is searched, because the numbers in this row are all smaller than the target.

Programmatic implementation (Java):

public class Solution {
    
    
    public boolean Find(int target, int [][] array) {
    
    

        int rows = array.length;
        int cols = array[0].length;
        int row = rows - 1;
        int col = 0;
        while (col < cols && row >= 0) {
    
    
            if (target > array[row][col]) {
    
    
                col++;
            } else if (target < array[row][col]) {
    
    
                row--;
            } else {
    
    
                return true;
            }
        }
        return false;
    }
}

2. The minimum number of JZ11 rotation array in "Jianzhi offer"

Title description:
insert image description here

Problem-solving ideas:
array represents an incrementally sorted rotating array, using left and right pointers to represent the left and right boundaries of the array respectively, and the subscript mid of the middle element of the array = (left+right)/2.

A standard ascending sort rotation array always has array[left] >= array[right], when array[left] < array[mid], it means the smallest element is on the right side of mid, so left = mid; array[left ] > array[mid], the smallest element is on the left side of mid, so right = mid. Until left and right are adjacent, array[right] is the smallest element. . But there are two special cases:

The first one, that is, the array rotation is the same as no rotation, that is, array[left] < array[right], and array[left] is the smallest element at this time.

The second type, array[left] == ​​array[right] == ​​array[mid], at this time the smallest element may be on the left side of mid or on the right side. Therefore, at this time, only the data between left and right can be traversed to find the smallest element.

Programming implementation:

import java.util.ArrayList;
public class Solution {
    
    
    public int minNumberInRotateArray(int [] array) {
    
    
        int l = 0;
        int r = array.length - 1;
        //退出条件:l=r,这时候数组里只剩下一个元素
        while (l < r) {
    
    
            //如果此时数组是严格递增的,直接返回最左边元素
            if (array[l] < array[r]) {
    
    
                return array[l];
            }

            int mid = (l + r) / 2;
            //array[mid] > array[l],说明mid在左边,更新l
            if (array[mid] > array[l]) {
    
    
                l = mid + 1;
                //array[mid] < array[l],说明mid在右边,更新r
            } else if (array[mid] < array[l]) {
    
    
                r = mid;
                //mid=l,说明左边有连续多个相同的值,l后移一位
            } else {
    
    
                l++;
            }
        }
        return array[l];
    }
}

3. Arrangement of JZ38 strings in "Jianzhi offer"

Title description:

insert image description here

Programmatic implementation (Java):

import java.util.*;
public class Solution {
    
    
    ArrayList<String> res = new ArrayList<>();
    ArrayList<Character> list = new ArrayList<>();
    boolean[] visited;
    public ArrayList<String> Permutation(String str) {
    
    
        if (str.length() == 0) {
    
    
            res.add("");
            return res;
        }
        
        visited = new boolean[str.length()];
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        dfs(chars, 0);

        return res;
    }

    void dfs(char[] arr, int k){
    
    
        //搜索到底,把一条路径加入到res集合中
        if(arr.length == k){
    
    
            res.add(charToString(list));
            return;
        }

        //剪枝。
        for(int i = 0; i < arr.length; i++){
    
    
            //从第二个字符开始,如果连续两个字符一样并且上一个没被访问过,说明arr[i]和arr[i - 1]在同一层,剪枝
            if(i > 0 && arr[i] == arr[i - 1] && visited[i - 1] == false){
    
    
                continue;
            }

            if(visited[i] == false){
    
    
                visited[i] = true;
                list.add(arr[i]);
                dfs(arr, k + 1);
                //回溯
                list.remove(list.size() - 1);
                visited[i] = false;
            }
        }
    }

    //把字符型集合转化为字符串
    String charToString(ArrayList<Character> list){
    
    
        StringBuilder str = new StringBuilder();
        for(int i = 0; i < list.size(); i++){
    
    
            str.append(list.get(i));
        }
        return str.toString();
    }
}

4. A certain number in the JZ44 number sequence of "Jianzhi offer"

Title description:
insert image description here

Problem-solving ideas:
For example, to find the 1001st digit,
1) There are 10 values ​​of 1 digit: 0~9, the number is 10×1=10, obviously 1001>10, skip these 10 values, Look for the 991st (1001-10) digits in the back.
2) There are 90 2-digit numbers: 10~99, the number is 90×2=180, and 991>180, continue to find the 811th (991-180) number in the back.
3) There are 900 3-digit values: 100~999, the number is 900×3=2700, and 811<2700, indicating that the 811th digit is in the value with 3 digits. Since 811=270×3+1, the 811th digit is the 270th value starting from 100, which is the second number of 370, which is 7.
According to this rule, other numbers can be obtained.
Programming implementation (Java):

import java.util.*;


public class Solution {
    
    
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param n int整型
     * @return int整型
     */
    public int findNthDigit (int n) {
    
    
        // write code here
        //bit记录某个数字是多少位的:123是3位,12是2位
        int bit = 1;
        //初始值:1~9为1,10~99为10,100~999为100
        long start = 1;
        //某个范围有多少个数字,1~9有9个,10~99有90个,100~999有900个
        long count = 9;
        if (n == 0) {
    
    
            return 0;
        }

        //找出是多少位的(范围)
        while (n > count) {
    
    
            n -= count;
            bit++;
            start *= 10;
            count = bit * start * 9;
        }

        //找出具体是那个数字
        String num = (start + (n - 1) / bit) + "";
        //获取那个数字的下标
        int index = (n - 1) % bit;
        return Integer.parseInt(num.charAt(index) + "");
    }
}

Guess you like

Origin blog.csdn.net/weixin_51405802/article/details/127646780