(AC) C easy understand 9ms


  • 0
    1

    #define search_min 0
    #define search_max 1
    void swap(int* t1,int* t2);
    void sort_second_max(int* nums,int left,int right,int* flag);
    void sort_min(int* nums,int left,int right);

    void printflist(int* num,int size)
    {
    for(int i=0;i<size;i++)
    printf("%d ",num[i]);
    printf("\n");
    }

    void nextPermutation(int* nums, int numsSize) {
    if (numsSize==1) return;

    int* flag=malloc(sizeof(int));
    *flag=false;
    for(int i=numsSize-2;i>=0;i--)
    {
        sort_second_max(nums,i,numsSize-1,flag);
        printflist(nums,numsSize);
        if(*flag==true){
            sort_min(nums,i+1,numsSize-1);
            free(flag);
            return;
        }
    }
    sort_min(nums,0,numsSize-1);
    free(flag);
    

    }

    void swap(int* t1,int* t2)
    {
    if(*t1==*t2)return;
    *t1^=*t2;
    *t2^=*t1;
    t1^=t2;
    }
    void sort_second_max(int
    nums,int left,int right,int
    flag)
    {
    int max=100;
    int idx=left;
    for(int i=left+1;i<=right;i++)
    {
    if(nums[i]>nums[left] && nums[i]<max){
    max=nums[i];
    idx=i;
    }
    }
    if(idx!=left){
    swap(&nums[idx],&nums[left]);
    *flag=true;
    }

    }
    void sort_min(int* nums,int left,int right)
    {
    if(left>=right) return;

    int pos=(left+right)>>1;
    int val=nums[pos];
    int idx=left;
    swap(&nums[right],&nums[pos]);
    
    for(int i =left;i<right;i++)
        if(val>nums[i])
            swap(&nums[idx++],&nums[i]);
    
    swap(&nums[idx],&nums[right]); 
    sort_min(nums,left,idx-1);
    sort_min(nums,idx+1,right);
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.