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

1 Permutation Sequence The set [1,2,3,…,n] contains a total of n! unique permutations.Given permutation sequence. 使用Next Permutation循环k次可以得到序列,但leetcode上提交会出现时间超过限制。下面采用数学法: 在,,那么排列的第一位元素一定是nums[p]。 假设有n个元素,第K个permutation是 设变量,利用上面的推断可知:

…….

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;}

累死累活不说,走马观花反而少了真实体验,

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

相关文章:

你感兴趣的文章:

标签云: