算法十七周解题报告

来源:互联网 发布:欧莱雅 曼秀雷敦 知乎 编辑:程序博客网 时间:2024/05/16 09:47
50. Pow(x, n)

Implement pow(xn)


解题思路:用分治的方法,每个自问题是求pow(x, n / 2), 可以讲算法复杂度降至 Ologn

不过题目非常狗血的考虑了负数边界这个问题,所以单独拿出来讨论即可。


代码:

class Solution {public:    double getPow(double x, signed long long int n) {        if(n == 1) return x;        if(n == 0) return 1;        if(n % 2 == 0){            double x1 = getPow(x, n / 2);            return x1 * x1;        }        else {            double x1 = getPow(x, (n - 1) / 2);            return x1 * x1 * x;        }    }    double myPow(double x, int n){        bool special = false;        if (n == -2147483648){            special = true;            n += 1;        }        long long int n1 = (n >= 0 ? n : -n);        x = getPow(x, n1) * (special == true ? x : 1);        return n >= 0 ? x : 1.0 / x;    }};


结果如下:



Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.


解题思路:用了归并排序的思想,每次只对前k个数排序,不过最坏情况依旧是onlogn

代码如下:

class Solution {public:    int findKthLargest(vector<int>& nums, int k) {        vector<int> a = maxKthNum(nums, k);        return a[k - 1];    }        vector<int> maxKthNum(vector<int>& num, int k) {vector<int>l, r;if (num.size() <= 1){return num;}int half = (num.size() - 1) / 2;l = vector<int>(num.begin(), num.begin() + half + 1);r = vector<int>(num.begin() + half + 1, num.end());l = maxKthNum(l, k);r = maxKthNum(r, k);return merge(l, r, k);}vector<int> merge(vector<int>& a, vector<int>& b, int k){k = k > a.size() + b.size() ? a.size() + b.size() : k;vector<int> res(k);int leftIndex = 0, rightIndex = 0, count = 0;while (leftIndex != a.size() && rightIndex != b.size() && count < k){res[count++] = a[leftIndex] > b[rightIndex] ? a[leftIndex++] : b[rightIndex++];}while (rightIndex != b.size() && count != k)res[count++] = b[rightIndex++];while (leftIndex != a.size() && count != k)res[count++] = a[leftIndex++];return res;}};
结果如下:



21

原创粉丝点击