您的位置:首页 > 编程语言 > C语言/C++

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

2015-05-22 11:21 363 查看
1 Permutation Sequence

The set [1,2,3,…,n] contains a total of n! unique permutations.Given nn and kk, return the kthk^{th} permutation sequence.

使用Next Permutation循环k次可以得到序列,但leetcode上提交会出现时间超过限制。下面采用数学法:

在n!n!个排列中,第一位元素相同的排列总是有(n−1)!(n-1)!个,如果p=k/(n−1)!p = k / (n-1)!,那么排列的第一位元素一定是nums[p]。

假设有n个元素,第K个permutation是

a1,a2,a3,........,ana_1, a_2, a_3, ..... ..., a_n

设变量K1=KK_1 = K,利用上面的推断可知:

a1=K1/(n−1)!a_1 = K_1 / (n-1)!

a2=K2/(n−2)!a_2 = K_2 / (n-2)!

K2=K1K_2 = K_1 % (n-1)!

…….

an−1=Kn−1/1!a_{n-1} = K_{n-1} / 1!

Kn−1=Kn−2/2!K_{n-1}= K_{n-2} /2!

an=Kn−1a_n = K_{n-1}

[code]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,将尾指针指向头指针。

[code]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;     
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: