標籤:c++ leetcode 格雷碼 鏈表劃分
1 Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.You should preserve the original relative order of the nodes in each of the two partitions.For example:
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
為了方便對鏈表第一個節點的操作,這裡要用到指向第一個節點的頭指標,從頭指標開始遍曆,我們要用一個變數記錄第一次出現節點中元素值大於目標值的位置,繼續向後遍曆,將小於目標的節點移動變數記錄的位置之前。
ListNode* partition(ListNode* head, int x) { if(head==NULL) return NULL; ListNode* result=new ListNode(0); result->next=head; ListNode* pre=result; ListNode* premid; ListNode* cur=head; ListNode* mid; bool flag=true; //用來標記找到第一個大於目標值的節點 while(pre->next) { if(pre->next->val<x) { if(flag) { pre=cur; cur=cur->next; } else { pre->next=cur->next; ListNode* reg=cur; cur=cur->next; premid->next=reg; reg->next=mid; premid=premid->next; } } else { if(flag) { premid=pre; mid=pre->next; flag=false; pre=cur; cur=cur->next; } else { pre=cur; cur=cur->next; } } } return result->next; }
Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2.
可以從對應的n位二進位碼字中直接得到n位格雷碼碼字,步驟如下:
(1)對n位二進位的碼字,從右至左,以0到n-1編號
(2) 如果二進位碼字的第i位和i+1位相同,則對應的格雷碼的第i位為0,否則為1(當i+1=n時,二進位碼字的第n位被認為是0,即第n-1位不變)。用公式表示:Gi=Bi?Bi+1,(n?1≥i≥0)。
vector<int> grayCode(int n) { vector<int> result; int len=1<<n; for(int i=0;i<len;i++) { result.push_back((i>>1)^i); } return result; }
LeetCode的medium題集合(C++實現)十七