[Solution] "100 Lectures on Algorithm Zero Basics" (Lesson 35) Basic Sort - Insertion Sort

Source code analysis

for(int i=1;i<nums1.size();i++) {
    
    
    int minn=nums1[i],j;
    for(j=i-1;j>=0;j--) {
    
    
        if(nums1[j]>minn) nums1[j+1]=nums1[j];
        else break;
    }
    nums1[j+1]=minn;
}

Traverse the array from front to back, find a position in front of each element where it should be placed, then push all the elements behind this position back one, and insert this element into it

88. Merge Two Sorted Arrays

Insertion sort after merging two arrays directly

class Solution {
    
    
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
    
    
        nums1.resize(m+n);
        for(int i=0;i<n;i++) nums1[m+i]=nums2[i];
        for(int i=1;i<nums1.size();i++) {
    
    
            int minn=nums1[i],j;
            for(j=i-1;j>=0;j--) {
    
    
                if(nums1[j]>minn) nums1[j+1]=nums1[j];
                else break;
            }
            nums1[j+1]=minn;
        }
    }
};

611. Number of valid triangles

class Solution {
    
    
public:
    int triangleNumber(vector<int>& nums) {
    
    
        int n=nums.size();
        for(int i=1;i<n;i++) {
    
    
            int minn=nums[i],j;
            for(j=i-1;j>=0;j--) {
    
    
                if(nums[j]>=minn) nums[j+1]=nums[j];
                else break;
            }
            nums[j+1]=minn;
        }
        int ans=0;
        for(int i=0;i<n;i++) {
    
    
            for(int j=i+1;j<n;j++) {
    
    
                int l=0,r=n-1;
                while(l<r) {
    
    
                    int mid=l+r+1>>1;
                    if(nums[mid]<nums[i]+nums[j]) l=mid;
                    else r=mid-1;
                }
                ans+=max(0,l-j);
            }
        }
        return ans;
    }
};

147. Insertion Sort on Linked List

The plug-in row of the linked list is simulated according to the idea of ​​the plug-in row. Since it is a singly linked list and cannot be traversed in reverse, you need to record the current point first.

class Solution {
    
    
public:
    ListNode* insertionSortList(ListNode* head) {
    
    
    ListNode* node=new ListNode(0);
    ListNode* pre=node;
    ListNode* cur=head;
    while(cur!=NULL){
    
    
            ListNode* tmp=cur->next;
            while(pre->next!=NULL&&pre->next->val<cur->val)pre=pre->next;
            cur->next=pre->next;
            pre->next=cur;
            pre=node;
            cur=tmp;
        }
    return node->next;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324145792&siteId=291194637