Full of Dry Goods: Detailed Explanation of Binary Search/Sorting Programming Questions

Iron juice~ Today I will share with you a detailed explanation of binary search/sorting programming questions (Niuke.com), full of dry goods, come on, let’s start making ⛳️ Let me tell you some small knowledge points: 1. Pointer variable name [
integer
] =* (pointer variable name + integer);
2. Knowledge point: double pointer

Double pointer means that in the process of traversing objects, instead of using a single pointer to access normally, two pointers are used (or even multiple in special cases), and the two pointers either access two linked lists in the same direction, or Access a linked list in the same direction (fast and slow pointers), or scan in the opposite direction (collision pointers), so as to achieve the purpose we need.

1. Search in one-dimensional array

describe

@param nums int整型一维数组 
 * @param numsLen int nums数组长度
 * @param target int整型 
 * @return int整型
 */
int search(int* nums, int numsLen, int target ) {
    
    
int left=0;
int right=numsLen-1;
while(left<=right)
{
    
    
    int mid=(left+right)/2;
    if(*(nums+mid)==target)
    return mid;      //找到了,返回下标值
    else if(*(nums+mid)>target)
    {
    
    
        right=mid-1;
    }

    else 
    {
    
    
         left=mid+1;
    }
}
return -1;         //找不到,返回-1
 }

Idea: Note-"Premise: The array is sorted in ascending order

a. First go to the subscript value of the leftmost number left, then take the subscript value of the rightmost number right

b. Calculate the value corresponding to the middle subscript value mid=(left+right)/2

c. Compare the nums[mid] value with the value you want to find:

When nums[mid]>search value, let right=mid-1 (indicating that the value to be searched is on the left side of mid);
when nums[mid]<search value, let left=mid+1 (indicating that the value to be searched for The value is on the right side of mid);
when nums[mid[=lookup value, returns the subscript value mid.

d. Loop condition: left<=right

Left<right is not allowed, assuming that once nums[left] is the left value adjacent to the search value, and nums[right] is the search value, at this time, when nums[left]<nums[right], left=mid+1=right , but the loop is exited at this time, and there is still one number in the array that has not been found, resulting in an erroneous result.
Find in one-dimensional array

2. Search in two-dimensional array

describe

 
 * @param target int整型 
 * @param array int整型二维数组 
 * @param arrayRowLen int array数组行数
 * @param arrayColLen int* array数组列数
 * @return bool布尔型
 */
#include <stdbool.h>
bool Find(int target, int** array, int arrayRowLen, int* arrayColLen ) {
    
    
    int row=0;
    int col=*arrayColLen-1;
    if(array==NULL||arrayRowLen<=0||*arrayColLen<=0)
    return false;
    while(row<arrayRowLen&&col>=0)
    {
    
    
        if(array[row][col]<target)    //则该元素所在的行中所有元素均不满足
    {
    
    
        row++;
    }
   else if(array[row][col]>target)   //则该元素所在的列中的所有元素均不满足
    {
    
    
        col--;
    }
    else                            //找到了
    {
    
    
       return true;
    }
    }
    return false;                 //找不到
}

Idea: This question is similar to searching in Young's matrix

Premise: Each row increases sequentially from left to right, and each column increases sequentially from top to bottom

a. Find the element in the upper right corner of the diagonal of the cuboid formed by the two-digit array

If the element value < lookup value, then the number of rows +1;
if the element value > lookup value, then the number of columns -1;

b. From the elements in the diagonal line where the upper right element is located, search down the line in turn until the lower left element is found, and the loop ends

c. Loop condition: number of rows<number of rows and columns of the two-dimensional array>=0

d. Special conditions: when the two-dimensional array is a null pointer (there is no value in the two-dimensional array), or the number of rows<=0 or the number of columns>=0.

Lookup in 2D array

3. Find the peak

find the peak

int findPeakElement(int* nums, int numsLen ) {
    
    
    int i=0,flag=1,num=0;                    //假设该数组为升序
    if(numsLen<3)                           //长度不足3
    {
    
    
        return ((*nums)<*(nums+1))?1:0;     //三目运算符
    }
    
    for(i=0;i<numsLen-1;i++)
    {
    
    
        if(*(nums+i)>*(nums+i+1))
        {
    
    
            flag=0;                       //此数组不为升序
            num=i;
            break;
        }
    }
    if(flag==1)                         //此数组为升序
        return numsLen-1;
    else
    return num;
}

Idea: need to classify and discuss

a. When the length is less than 3, the two elements are directly compared

b. When the length is greater than or equal to 3, assuming that the array is an ordered array (flag=1), the array is traversed from front to back, and at the same time, it is judged whether the previous value is greater than the latter value. When the first peak value is found in the array , let num record the first peak index value, and jump out of the loop immediately (flag=0, the array is not an ascending array)

c. Determine whether the value of the flag has changed

If flag=1, return the value of the array length -1;
if flag=0, return the value of num;

4. Reversed pairs in the array

array in reverse order

 @param data int整型一维数组 
 * @param dataLen int data数组长度
 * @return int整型
 */
int InversePairs(int* data, int dataLen ) {
    
    
   unsigned int count=0;
   int i=0,j=0;
   for(i=0;i<dataLen-1;i++)     //进行的总趟数
   {
    
    
    for(j=i+1;j<dataLen;j++)   //每趟需要进行比较的总对数
    {
    
    
        if(data[i]>data[j])
        count++;
    }
   }
    return count%1000000007;
}

Idea: Note: Here, the composition of the reverse order pair does not require that the two elements must be two adjacent elements. As long as the two non-adjacent elements meet the conditions of the reverse order pair, they are also a pair

Method: Use double pointers, let one pointer point to the address of the first element of the string, and let the address of the second element of the other string

a. The first time: the second pointer moves backwards from the starting position it points to until it moves to the address of the last element. Each time it moves, it needs to be compared with the element pointed to by the first pointer (equivalent to determine the logarithms to compare for each pass)

b. Second time: Let the first pointer move back one position, the second pointer points to the address of the third element, and move backwards in turn until it moves to the address of the last element. Compare with the element pointed to by the first pointer (equivalent to determining the total number of passes that need to be made)

c. Repeat the loop until the first pointer points to the address of the penultimate element, which is the last comparison
reversed pairs in an array

5. Rotate the smallest number in the array

Rotate the smallest number in an array

 * @param rotateArray int整型一维数组 
 * @param rotateArrayLen int rotateArray数组长度
 * @return int整型
 */
int minNumberInRotateArray(int* rotateArray, int rotateArrayLen ) {
    
    
int left=0;
int right=rotateArrayLen-1;
while(left<right)                                    //循环条件
{
    
    
    int mid=(left+right)/2;
    if(rotateArray[mid]<rotateArray[right])           //寻找范围在左边
    {
    
    
        right=mid;
    }
    else if(rotateArray[mid]>rotateArray[right])     //寻找范围在右边
    {
    
    
        left=mid+1;
    }
    else {
    
    
        right--;
    }
}
return rotateArray[left];
}

Idea: premise: the array is in ascending order

Popularity: Rotating Array Features: Divide an array into two groups of ordered arrangements

a. First take the leftmost digital subscript value as Left, and take the rightmost digital subscript value as right

b. Calculate the value corresponding to the middle subscript mid=(left+right)/2, and compare it with the rightmost digital value

If rotateArray[mid]<rotateArray[right], it means that the values ​​on the right side of mid are sorted in ascending order, indicating that the number you are looking for is in the left range of mid (including mid), let right=mid, and calculate the value corresponding to mid, Compare with rotateArray[right];
if rotateArray[mid]>rotateArray[right], it means that the number you are looking for is in the left range of mid (excluding mid), let left=mid+1, and calculate the value corresponding to mid Value, compared with rotateArray[right];

c. When rotateArray[mid]=rotateArray[right], let right-1, left remain unchanged, calculate the value corresponding to mid, and compare with rotateArray[right]

d. Loop condition: left<right, no need to add left=right, this is not a search (need to traverse each element in the array).
Rotate the smallest number in an array

6. Compare version numbers

insert image description here
compare version numbers

 *比较版本号
 * @param version1 string字符串 
 * @param version2 string字符串 
 * @return int整型
 */
#include <string.h>
int compare(char* version1, char* version2 ) 
{
    
    
    int len1=strlen(version1);             //字符串1的元素总个数
    int len2=strlen(version2);            //字符串2的元素总个数
    int i=0,j=0;
    for(i=0,j=0;i<len1||j<len2;)                
    {
    
    
        int n1=0,n2=0;                 /*第一个点字符之前的数字比较完毕,再进行第二个点字符之前数字的比较,此处已经将
                                       原存储的数字清空了,并不影响下一次字符的存储*/
        while(i<len1&&version1[i]!='.')   
        //找到每个点字符出现前的字符串
        {
    
    
            n1=n1*10+(version1[i]-'0');  //将数字字符进行转化为数字,依次将个数字存储起来
            i++;   
        }
        i++;                             //跳过点字符
        while(j<len2&&version2[j]!='.')
        {
    
    
            n2=n2*10+(version2[j]-'0'); //将数字字符进行转化为数字,依次将个数字存储起来
            j++;                     
        }
        j++;                           //跳过点字符
        if(n1>n2)
        {
    
    
            return 1;
        }
        else if(n1<n2)
        {
    
    
            return -1;
        }
     }
     return 0;
}

Idea: Ignore the leading 0, skip the dot character, and stop before the dot character every time for numerical comparison

Method: Use double pointers, let one pointer point to the address of the first element of a string, and let the other pointer point to the address of the first element of another string

a. Two pointers traverse backwards in sequence

b. Because it is necessary to compare, the number characters are not easy to compare, it needs to be converted into the corresponding number ('number'-'0'), and then each number is stored in turn (n=n*10+('number '-'0')) (0 will not have any effect on the formula, that is: the value of n has no change)

c. Loop condition: the dot character is not encountered and the two pointers have not reached the address behind the last element of the string it points to

Thank you for watching ✨
insert image description here

Guess you like

Origin blog.csdn.net/m0_74808907/article/details/129974862