LeetCode的medium題集合(C++實現)十七

來源:互聯網
上載者:User

標籤: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++實現)十七

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.