【LeetCode】Algorithms 题集(六)

Sort Colors
题意:

     Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

     Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

     Note:
     You are not suppose to use the library's sort function for this problem.

思路:

     就是要你自己写个排序。下面用了快排,已优化。

代码:

class Solution {
public:
    void sortColors(int A[], int n) {
        quickSort(A,0,n-1);
    }

    void quickSort(int num[], int l, int r)
    {
        if(l >= r) return;

        int k = l + rand()%(r-l+1);
        int t = num[k];
        num[k] = num[l];
        num[l] = t;

        if(r - l + 1 < 8){
            for(int i = l+1;i <= r;++i)
                if(num[i] < num[i-1])
                {
                    int j,t = num[i];
                    for(j = i-1;j >= 0 && num[j] > t;j--)
                        num[j+1] = num[j];
                    num[j+1] = t;
                }
            return;
        }

        int i = l,j = r,key = num[l];
        while(i < j)
        {
            while(i < j && num[j] > key)
                j--;
            if(i < j) num[i++] = num[j];

            while(i < j && num[i] < key)
                i++;
            if(i < j) num[j--] = num[i];
        }
        num[i] = key;

        quickSort(num,l,i-1);
        quickSort(num,i+1,r);
    }
};


Find Peak Element
题意:

     A peak element is an element that is greater than its neighbors.

    Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
 
    The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

    You may imagine that num[-1] = num[n] = -∞.

    For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

思路:

     在一个序列里找出一个数,它比左边的数大,比右边的数小。序列的第一个数的左边和最后一个数的右边都认为是无穷小的数。

     大概有两种解法,一个是直接用 INT_MIN 作为无穷小的数进行比较,见下面 C++ 代码,另一个是对第一个数和最后一个数的条件变量单独判断,不给了。

代码:

class Solution {
public:
    int findPeakElement(const vector<int> &num) {
        int n = num.size();

        if(n == 1) return 0;

        for(int i = 0;i < n;++i)
        {
            int pre = (i==0?INT_MIN:num[i-1]);
            int next = (i==n-1?INT_MIN:num[i+1]);

            if(num[i] > pre && num[i] > next)
                return i;
        }
    }
};


Remove Element
题意:

     Given an array and a value, remove all instances of that value in place and return the new length.

     The order of elements can be changed. It doesn't matter what you leave beyond the new length.

思路:

     必须用 O(n) 的算法。考虑在原数组上直接移位放置的操作。记录两个下标,一个 cur, 代表当前的不用删除的元素应该放置的位置,另一个代表遍历到的下标。

代码:

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int cur = 0;
        int diff_num = 0;
        for(int i = 0;i < n;++i)
        {
            if(A[i] != elem)
            {
                A[cur++] = A[i];
                diff_num++;
            }
        }
        return diff_num;
    }
};

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

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

思路:

     通过把 3 位的格雷码列出来,可以发现,n 位的格雷码,是由 n-1 位的格雷码,加上 1<<(n-1) 与 n-1 格雷码逆序的和

代码:

class Solution {
public:
    vector<int> grayCode(int n) {
        if(n == 0)
        {
            vector<int> ans(1,0);
            return ans;
        }

        int base = 1<<(n-1);
        vector<int> ans(grayCode(n-1));
        int size = ans.size();

        for(int i = size-1;i >= 0;i--)
        {
            ans.push_back(base + ans[i]);
        }
        return ans;
    }
};

Swap Nodes in Pairs
题意:

      Given a linked list, swap every two adjacent nodes and return its head.

     For example,
     Given 1->2->3->4, you should return the list as 2->1->4->3.

     Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

思路:

     交换链表中每队相邻节点,必须使用 O(1) 的空间,并且不能修改节点的值。主要考虑对 head 节点单独处理和链表交换节点的操作。

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        ListNode* cur = head;
        ListNode* last = head;
        bool flag = true;

        while(cur != NULL && cur->next != NULL)
        {
            if(flag)
            {
                flag = false;
                head = cur->next;
                ListNode* tmp = cur->next->next;
                head->next = cur;
                cur->next = tmp;
                last = cur;
                cur = cur->next;
            }
            else
            {
                last->next = cur->next;
                ListNode* tmp = cur->next->next;
                last->next->next = cur;
                cur->next = tmp;
                last = cur;
                cur = cur->next;
            }
        }
        return head;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值