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