LeetCode的medium题集合(C++实现)十

1 Permutation Sequence
The set [1,2,3,…,n] contains a total of n! unique permutations.Given n and k, return the kth permutation sequence.
使用Next Permutation循环k次可以得到序列,但leetcode上提交会出现时间超过限制。下面采用数学法:
n! 个排列中,第一位元素相同的排列总是有 (n1)! 个,如果 p=k/(n1)! ,那么排列的第一位元素一定是nums[p]。
假设有n个元素,第K个permutation是
a1,a2,a3,........,an
设变量 K1=K ,利用上面的推断可知:

a1=K1/(n1)!
a2=K2/(n2)!
K2=K1
…….
an1=Kn1/1!
Kn1=Kn2/2!
an=Kn1

string getPermutation(int n, int k) {
         vector<int> nums(n);  
        int pCount = 1;  
        for(int i = 0 ; i < n; ++i) 
        {  
            nums[i] = i + 1;  
            pCount *= (i + 1);  
        }  

        k--;  
        string res = "";  
        for(int i = 0 ; i < n; i++)
        {  
            pCount = pCount/(n-i);  
            int selected = k / pCount;  
            res += ('0' + nums[selected]);  

            for(int j = selected; j < n-i-1; j++)  
                nums[j] = nums[j+1];  
            k = k % pCount;  
        }  
        return res;  
    }

2 Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
先从头指针开始向后遍历直到链表尾端,用变量count记录链表长度。然后将k对count取模,将头指针向后移动count-k-1,将它的下个指针指向
NULL,将尾指针指向头指针。

ListNode* rotateRight(ListNode* head, int k) {
        if(head==NULL) return NULL;
        ListNode* last=head;
        ListNode* mid=head;
        ListNode* tail=head;
        int count=0;
        while(last!=NULL)
        {
            tail=last;
            last=last->next;
            count++;
        }
        k%=count;
        if(k==0) return head;
        int end=count-k;
        while(--end>0)
        {
            mid=mid->next;
        }
         ListNode* res=mid->next;
         mid->next=NULL;
         tail->next=head;
         return res;     
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值